实现接口Runnable类(线程)

 1 package bao7;
 2 
 3 public class TextMaiPiao
 4 {
 5 
 6     public static void main(String[] args)
 7     {
 8         //买票
 9         MaiPiao mp=new MaiPiao();
10         //启动第一个窗口
11         Thread t1=new Thread(mp,"窗口一");
12         t1.start();
13         
14         //启动第二个窗口
15         Thread t2=new Thread(mp,"窗口二");
16         t2.start();
17         
18         //启动第三个窗口
19         Thread t3=new Thread(mp,"窗口三");
20         t3.start();
21     }
22 
23 }
 1 package bao7;
 2 
 3 public class MaiPiao implements Runnable
 4 {
 5     int piaos=10;
 6     @Override
 7     public void run() 
 8     {
 9         maiPiao();
10 
11     }
12     
13     public void maiPiao()
14     {
15         
16         while(true)
17         {
18         //同步标志
19         Object mutex="";
20         //同步块
21         synchronized (mutex) 
22         {
23             if(piaos>0)
24             {
25             try 
26             {
27                 Thread.sleep(1000);
28             } 
29             catch (InterruptedException e)
30             {
31                 e.printStackTrace();
32             }
33             
34             piaos--;
35             System.out.println(Thread.currentThread().getName()+"剩余票数="+piaos);
36             }
37         }
38         }
39     }
40 
41 }

 

posted @ 2016-06-04 23:39  明天会更好!!!!  阅读(170)  评论(0)    收藏  举报