以runnabke方式实现多线程

 1 /**
 2  * @author lisa
 3  * @create 2020-08-10-21:14
 4  */
 5 public class RunnableTest {
 6     public static void main(String[] args) {
 7         runnable();
 8 
 9     }
10     static void runnable(){
11 
12         Runnable r=new Runnable() {
13             int ticket=100;
14             @Override
15             public void run() {
16                 if (ticket > 0) {
17                     synchronized (this) {
18                         while (true) {
19                             if (ticket > 0) {
20                                 System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
21                                 ticket--;
22                             } else {
23                                 break;
24 
25                             }
26                         }
27                     }
28                 }
29             }
30         };
31 
32         Thread th1=new Thread(r);
33         Thread th2=new Thread(r);
34         Thread th3=new Thread(r);
35         th1.start();
36         th2.start();
37         th3.start();
38 
39     }
40 }

可以看到每个线程在进入取票系统时候都要排队实际上是单线程,如果考虑到每个线程如果执行的时间如果很长,这段时间可以忽略不计

runnable中的属性天然可被共享

posted on 2020-08-11 01:13  落华12580  阅读(119)  评论(0)    收藏  举报

导航