Java2实用教程(第二版)程序代码——第十九章 Java多线程机制

  1//例子1
  2public class Example19_1 
  3{  public  static void main(String args[])
  4   {  Lefthand left;
  5      Righthand right;  
  6      left=new Lefthand() ;//创建线程。
  7      right=new Righthand();
  8      left.start();   //线程开始运行后,Lefthand类中的run方法将被执行。
  9      right.start();
 10   }

 11}

 12class Lefthand extends Thread
 13{  public void run()
 14   {  for(int i=1;i<=5;i++)
 15       {  System.out.print("A");
 16          try {
 17               sleep(500);
 18              }

 19         catch(InterruptedException e){}
 20       }

 21   }
 
 22}

 23class Righthand extends Thread
 24{  public void run()
 25   {  for(int i=1;i<=5;i++)
 26         {  System.out.print("B");
 27           try{ sleep(300);
 28              }

 29           catch(InterruptedException e){}
 30         }

 31   }
 
 32}

 33
 34//例子2
 35import java.awt.*;import java.awt.event.*;
 36public class Example19_3
 37{  public static void main(String args[])
 38   {  Mywin win=new Mywin();win.pack();
 39   }

 40}

 41class Mywin extends Frame implements Runnable
 42{  Button b=new Button("ok");int x=5;
 43   Thread bird=null;
 44   Mywin()
 45   {  setBounds(100,100,120,120);setLayout(new FlowLayout());
 46      setVisible(true);
 47      add(b);b.setBackground(Color.green);
 48      addWindowListener(new WindowAdapter()
 49           {  public void windowClosing(WindowEvent e)
 50              {  System.exit(0);
 51              }

 52           }
);
 53      bird=new Thread(this);//创建一个新的线程,窗口做目标对象,
 54                          //替线程bird实现接口Runnable。
 55      bird.start();         //在创建窗口时又开始了线程bird。
 56   }

 57   public void run()       //实现bird的操作。
 58   {  while(true)
 59       {  x=x+1;
 60          if(x>100) x=5;
 61          b.setBounds(40,40,x,x);
 62          try{  bird.sleep(200);
 63             }

 64          catch(InterruptedException e){} 
 65       }

 66   }

 67}

 68
 69//例子3
 70import java.applet.*;import java.awt.*;import java.awt.event.*;   
 71public class Example19_3 extends Appletimplements ActionListener,Runnable
 72{  TextField  text1,text2;
 73   boolean boo;  int x=0
 74   Thread Scrollwords=null
 75   public void init()
 76   {  Scrollwords=new Thread(this);
 77      text1=new TextField(10);
 78      text2=new TextField(10);
 79      add(text1); add(text2);
 80      text1.addActionListener(this); 
 81   }

 82   public void start()
 83   {  boo=false;
 84      try{  Scrollwords.start();
 85         }

 86      catch(Exception ee) { }
 87   }

 88   public void run ()
 89   {  while(true)
 90         {  x=x+5;
 91            if(x>200)
 92               x=0;
 93            repaint();
 94            try{  Scrollwords .sleep(80);
 95               }
 
 96            catch(InterruptedException e){}
 97            if(boo)
 98              {  return;           //结束run方法,导致线程死亡。
 99              }

100          }

101   }

102   public void paint(Graphics g)
103   {  g.drawString("欢 迎 使 用 本 字 典",x,70);
104   }

105   public void actionPerformed(ActionEvent e)
106   {  if(text1.getText().equals("boy"))
107      {  text2.setText("男孩");
108      }

109     else if(text1.getText().equals("moon"))
110      {  boo=true;         //将boo的值设置为true,以便杀死线程Scrollwords。
111      }

112     else
113      {  text2.setText("没有该单词");
114      }

115   }

116}

117
118//例子4
119import java.applet.*;import java.awt.*;import java.awt.event.*;
120public class Example19_4 extends Applet implements Runnable
121{  Thread left ,right; Graphics mypen; int x,y;
122   public void init()
123   {  left=new Thread(this);right=new Thread(this);
124      x=10;y=10;mypen=getGraphics();
125   }

126   public void start()
127   {  left.start();right.start();
128   }

129   public void run()
130   {  while(true)
131      if(Thread.currentThread()==left)
132         { x=x+1;
133           if(x>240) x=10;
134           mypen.setColor(Color.blue);
135           mypen.clearRect(10,10,300,40); 
136           mypen.drawRect(10+x,10,40,40); 
137           try{  left.sleep(60);
138              }

139           catch(InterruptedException e){}
140          }

141        else if(Thread.currentThread()==right)
142          {  y=y+1;
143             if(y>240) y=10; mypen.setColor(Color.red); 
144              mypen.clearRect(10,90,300,40); 
145              mypen.drawOval(10+y,90,40,40);
146              try{  right.sleep(60);
147                 }

148              catch(InterruptedException e){}
149           }

150      }

151   }

152   public void stop()
153   {  left=null;right=null;
154   }

155}

156
157//例子5
158import java.awt.*;import java.awt.event.*;
159import java.applet.*;
160public class Example19_5 extends Applet 
161                  implements Runnable
162{  Thread 红色球,兰色球; 
163   Graphics redPen,bluePen;
164   double t=0;
165   public void init()
166   {  红色球=new Thread(this);
167      兰色球=new Thread(this);
168  redPen=getGraphics();bluePen=getGraphics();
169  redPen.setColor(Color.red); bluePen.setColor(Color.blue);
170   }

171   public void start()
172   {  红色球.start();兰色球.start();
173   }

174   public void run()
175   {  while(true)
176      {  t=t+0.2;
177         if(Thread.currentThread()==红色球) 
178            {  if(t>20)  t=0;
179               redPen.clearRect(0,0,38,300);
180               redPen.fillOval(20,(int)(1.0/2*t*t*3.8),16,16);
181               try{  红色球.sleep(50);
182                  }

183               catch(InterruptedException e){}
184             }

185          else if(Thread.currentThread()==兰色球)
186            {  bluePen.clearRect(38,0,500,300);
187               bluePen.fillOval(38+(int)(16*t),(int)(1.0/2*t*t*3.8),16,16);
188               try{  兰色球.sleep(50);
189                  }

190               catch(InterruptedException e){}
191            }
 
192      }
   
193   }
 
194}

195
196//例子6
197import java.applet.*;import java.awt.*;
198import java.awt.event.*;
199public class Example19_6 extends Applet implements ActionListener
200{  Toolkit toolkit;Button button; 
201   public void init()
202   {  toolkit=getToolkit();//获得一个工具包对象 
203      button=new  Button("确定");add(button);
204      button.addActionListener(this); 
205   }

206   public void actionPerformed(ActionEvent e)
207   {  if(e.getSource()==button)
208       {  for(int i=0;i<=9;i++)
209             {  toolkit.beep();
210                try {  Thread.sleep(500);
211                    }
      //每隔半秒钟发出嘟声
212               catch(InterruptedException e1){}
213             }

214       }

215   }

216}

217
218//例子7
219import java.applet.*;import java.awt.*;
220import java.awt.event.*;
221public class Example19_7 extends Applet implements Runnable
222{  int money=100;TextArea text1,text2;
223   Thread 会计,出纳;
224   public void init()
225   {  会计=new Thread(this); 出纳=new Thread(this);//创建两个线程:会计、出纳。
226      text1=new TextArea(20,8); text2=new TextArea(20,8);
227      add(text1);add(text2);
228   }

229   public void start()
230   {  会计.start();出纳.start();                 //线程开始。
231   }

232   public synchronized void 存取(int number) //存取方法。
233   {  if(Thread.currentThread()==会计)
234       {  for(int i=1;i<=3;i++//会计使用存取方法存入90元,存入30元,稍歇一下,
235            {  money=money+number;        //这时出纳仍不能使用存取方法,
236               try {  Thread.sleep(1000);  //因为会计还没使用完存取方法。
237                   }
             
238               catch(InterruptedException e){}
239               text1.append("\n"+money);
240            }

241       }

242      else if(Thread.currentThread()==出纳)
243      {  for(int i=1;i<=2;i++//出纳使用存取方法取出30元,取出15元,稍歇一下,
244            {  money=money-number/2;      //这时会计仍不能使用存取方法,
245               try { Thread.sleep(1000); //因为出纳还没使用完存取方法。
246                   }

247               catch(InterruptedException e){}
248               text2.append("\n"+money);
249            }

250      }

251   }

252   public void run()
253   {  if(Thread.currentThread()==会计||Thread.currentThread()==出纳)
254         {  for(int i=1;i<=3;i++//从周一到周三会计和出纳都要使用帐本。
255                {  存取(30);
256                }

257         }
 
258   }

259}
 
260
261//例子8
262import java.applet.*;import java.awt.*;
263import java.awt.event.*;
264class 售票员
265{  int 五元钱的个数=2,十元钱的个数=0,二十元钱的个数=0; String s=null;
266   public synchronized void  售票规则(int money)
267   {  if(money==5)     //如果使用该方法的线程传递的参数是5,就不用等待。
268        {  五元钱的个数=五元钱的个数+1
269           s= "给您入场卷您的钱正好";
270           Example19_8.text.append("\n"+s);
271        }

272      else if(money==20)           
273        {  while(五元钱的个数<3)
274            {  try { wait();    //如果使用该方法的线程传递的参数是20须等待。
275                   }

276               catch(InterruptedException e){}
277            }

278           五元钱的个数=五元钱的个数-3;
279           二十元钱的个数=二十元钱的个数+1;
280           s="给您入场卷"+"  您给我20,找您15元";
281           Example19_8.text.append("\n"+s);
282        }

283       notifyAll();
284   }

285}

286public class Example19_8 extends Applet implements Runnable
287{  售票员 王小姐;
288   Thread 张平,李明;  //创建两个线程。
289   static TextArea text; 
290   public void init()
291   {  张平=new Thread(this);李明=new Thread(this);
292      text=new TextArea(10,30);add(text);
293      王小姐=new 售票员(); 
294   }
 
295   public void start()
296   {  张平.start();李明.start(); 
297   }

298   public void run()
299   {  if(Thread.currentThread()==张平)
300        {  王小姐.售票规则(20);
301        }

302      else if(Thread.currentThread()==李明)
303        {  王小姐.售票规则(5);
304        }

305   }
   
306}

307
308//例子9
309import java.awt.event.*;
310import java.awt.*;import java.util.Date;
311class Example19_9 extends Frame implements Runnable,ActionListener
312{  Thread thread=null; TextArea text=null;
313   Button b_start=new Button("Start"),b_stop=new Button("Stop");
314   Example19_9()
315   {  thread=new Thread(this);
316      text=new TextArea();add(text,"Center");
317      Panel p=new Panel();p.add(b_start);p.add(b_stop); 
318      b_start.addActionListener(this);
319      b_stop.addActionListener(this) ;
320     add(p,"North");setVisible(true);
321     setSize(500,500);pack();setSize(500,500);
322     setResizable(false);                     //让窗口的大小不能被调整。
323     addWindowListener(new WindowAdapter()
324                   {  public void windowClosing(WindowEvent e)
325                     {System.exit(0);
326                     }

327                   }
);
328   }

329   public void actionPerformed(ActionEvent e)
330   {  if(e.getSource()==b_start)
331        {
332           if(!(thread.isAlive()))
333              {  thread=new Thread(this);
334              }
    
335          try {  thread.start();
336              }

337          catch(Exception e1)
338              {  text.setText("线程没有结束run方法之前,不要再调用start方法");
339              }
  
340       }

341      else if(e.getSource()==b_stop)
342       {  thread.interrupt();
343       }

344   }

345   public void run()
346   {  while(true)
347           {  text.append("\n"+new Date());
348               try{  thread.sleep(1000);
349                  }

350               catch(InterruptedException ee)
351                  {  text.setText("我被消灭");return;//结束run语句,消灭该线程。
352                  }

353            }
 
354   }

355   public static void main(String args[])
356   {  Example19_9 tt=new Example19_9();
357   }

358}

359
360//例子10 
361import java.awt.*;import java.awt.event.*;import java.applet.*;
362public class Example19_10 extends Applet implements Runnable,ActionListener
363{  Button b=new Button("go");TextField text=null;
364   Thread 发令员,运动员_1,运动员_2;
365   int x=10;//线程运动的起始位置。
366   Graphics mypen=null
367   public void init()
368   {  b.addActionListener(this);text=new TextField(20);
369      发令员=new Thread(this);运动员_1=new Thread(this);运动员_2=new Thread(this);
370      add(b);add(text);
371      mypen=getGraphics();
372   }

373   public void start()
374   {  发令员.start();
375   }

376   public void actionPerformed(ActionEvent e)
377   {  发令员.interrupt();//点击按扭结束发令员的生命。
378   }

379   public void run()
380   {  if(Thread.currentThread()==发令员)
381      while(true)
382        {  text.setText("准备跑 ");text.setText("");
383           try {  发令员.sleep(30);
384               }

385           catch(InterruptedException e)
386               //点击按扭结束生命,并让运动员_1开始跑。
387  text.setText("");
388                   运动员_1.start(); break
389               }
  
390        }

391     }

392    if(Thread.currentThread()==运动员_1)
393     {  while(true)
394        {   x=x+1;
395            mypen.setColor(Color.blue);
396            mypen.clearRect(10,80,99,100);//显示线程运动的动画。  
397            mypen.fillRect(x,85,5,5); 
398            try  {  运动员_1.sleep(10);
399                 }

400            catch(InterruptedException e)
401                 {         //通知运动员_2开始跑,运动员_1结束生命: 
402运动员_2.start(); return;
403}

404            if(x>=100
405                {  运动员_1.interrupt();//运动员_1当跑到100米处时结束生命。
406                }

407        }

408     }
 
409     if(Thread.currentThread()==运动员_2)
410     {  while(true)
411        {   x=x+1;
412            mypen.setColor(Color.red);
413            mypen.clearRect(105,80,150,100);//显示线程运动的动画。 
414            mypen.fillRect(x+5,85,7,7); 
415            try  {  运动员_2.sleep(10);
416                 }

417            catch(InterruptedException e)
418                 {text.setText("到达终点"); return
419                 }

420            if(x>=200)             //运动员_2跑到200米处时结束生命。
421                {  运动员_2.interrupt();
422                }

423        }

424     }

425   }
  
426}

427
428//例子11
429import java.awt.*;import java.util.*;import java.awt.event.*;
430import java.awt.geom.*;import java.applet.*;
431public class Example19_11 extends Applet implements Runnable
432{   Thread 时针=null,分针=null,秒针=null;//用来表示时针,分针和秒针的线程.
433     //表示时针,分针,秒针端点的整型变量:
434     int hour_a,hour_b,munite_a,munite_b,second_a,second_b;
435     //用来获取当前时间的整型变量:
436     int hour=0,munite=0,second=0;
437     //用来绘制时针,分针和秒针的Grapghics对象:
438     Graphics g_second=null,g_munite=null,g_hour=null;
439     //用来存放表盘刻度的数组,供指针走动时使用:
440     double point_x[]=new double[61], point_y[]=new double[61] ;
441     //用来存放表盘刻度的数组,供绘制表盘使用:
442     double scaled_x[]=new double[61], scaled_y[]=new double[61] ;
443    //用来判断小程序是否重新开始的变量:
444      int start_count=0;
445   public void init()
446   {g_hour=this.getGraphics();   g_hour.setColor(Color.cyan);
447    g_second=this.getGraphics(); g_second.setColor(Color.red); 
448    g_munite=this.getGraphics(); g_munite.setColor(Color.blue);
449    g_second.translate(200,200);//进行坐标系变换,将新坐标系原点设在(200,200)处。
450    g_munite.translate(200,200);
451    g_hour.translate(200,200);
452    point_x[0]=0;point_y[0]=-120//各个时针十二点处的位置坐标(按新坐标系的坐标)。
453    scaled_x[0]=0;scaled_y[0]=-140//十二点处的刻度位置坐标(按新坐标系的坐标)。
454    double jiaodu=6*Math.PI/180;
455     //表盘分割成60分,将分割点处的坐标存放在数组中:
456     for(int i=0;i<60;i++)
457{ point_x[i+1]=point_x[i]*Math.cos(jiaodu)-
458Math.sin(jiaodu)*point_y[i];
459point_y[i+1]=point_y[i]*Math.cos(jiaodu)+ 
460point_x[i]*Math.sin(jiaodu);
461              }

462      point_x[60]=0;point_y[60]=-120;//十二点各个时针的位置坐标(按新坐标系的坐标)。
463    //表盘分割成60分,将分割点处的坐标存放在数组中:
464     for(int i=0;i<60;i++)
465{ scaled_x[i+1]=scaled_x[i]*Math.cos(jiaodu)-
466Math.sin(jiaodu)*scaled_y[i];
467scaled_y[i+1]=scaled_y[i]*Math.cos(jiaodu)+
468scaled_x[i]*Math.sin(jiaodu);
469}

470scaled_x[60]=0; scaled_y[60]=-140;//十二点处刻度位置坐标(按新坐标系的坐标)。
471  }

472   public void start()
473   //每当小程序重新开始时,首先消灭线程,然后重新开始创建线程。
474     if(start_count>=1)
475     {秒针.interrupt();分针.interrupt();时针.interrupt();
476     }

477     秒针=new Thread(this);分针=new Thread(this);
478     时针=new Thread(this);
479     秒针.start();分针.start();时针.start(); 
480     start_count++;if(start_count>=2) start_count=1
481   }

482   public void stop()
483   {秒针.interrupt();分针.interrupt();时针.interrupt();
484   }

485   public void paint(Graphics g)
486   {  //每当小程序重新绘制自己时,重新开始创建线程:
487          this.start();
488         //绘制表盘的外观:
489         g.drawOval(50,50,300,300);//表盘的外圈。
490         g.translate(200,200);
491        //绘制表盘上的小刻度和大刻度:
492        for(int i=0;i<60;i++)
493           if(i%5==0)
494                { g.setColor(Color.red);
495                  g.fillOval((int) scaled_x[i],(int) scaled_y[i],8,8);
496                }

497             else
498               g.fillOval((int) scaled_x[i],(int) scaled_y[i],3,3);
499           }

500  }

501  public void run()
502  //获取本地时间:
503    Date date=new Date();String s=date.toString();
504    hour=Integer.parseInt(s.substring(11,13)); 
505    munite=Integer.parseInt(s.substring(14,16));
506    second=Integer.parseInt(s.substring(17,19));
507    if(Thread.currentThread()==秒针)
508      {  second_a=(int)point_x[second];second_b=(int)point_y[second];
509         g_second.drawLine(0,0,second_a,second_b); //秒针的初始位置。
510         g_second.drawString("",second_a,second_b);
511         int i=second;
512         while(true)  //秒针开始行走,每一秒走6度.
513         {try{秒针.sleep(1000);
514          Color c=getBackground();g_second.setColor(c);
515          g_second.drawLine(0,0,second_a,second_b);//用背景色清除前一秒时的秒针。
516          g_second.drawString("",second_a,second_b);
517                  //如果这时秒针与分针重合,恢复分针的显示:
518                  if((second_a==munite_a)&&(second_b==munite_b))
519                   { g_munite.drawLine(0,0,munite_a,munite_b);
520                     g_munite.drawString("",munite_a,munite_b);
521                   }
 
522                  //如果这时秒针与时针重合,恢复时针的显示:
523                  if((second_a==hour_a)&&(second_b==hour_b))
524                   { g_hour.drawLine(0,0,hour_a,hour_b);
525                    g_hour.drawString("",hour_a,hour_b);
526                   }
 
527                 }

528             catch(InterruptedException e)
529                 { Color c=getBackground();g_second.setColor(c);
530                  g_second.drawLine(0,0,second_a,second_b);//用背景色清除秒针。
531                  g_second.drawString("",second_a,second_b);
532                  return;
533                 }

534             //秒针向前走一个单位: 
535     second_a=(int)point_x[(i+1)%60];
536     second_b=(int)point_y[(i+1)%60];//每一秒走6度(一个单位格)。
537     g_second.setColor(Color.red); 
538     g_second.drawLine(0,0,second_a,second_b);   //绘制新的秒针。
539     g_second.drawString("",second_a,second_b);
540             i++;
541           }

542      }
  
543    if(Thread.currentThread()==分针)
544      {  
545          munite_a=(int)point_x[munite];munite_b=(int)point_y[munite];
546          g_munite.drawLine(0,0,munite_a,munite_b);//分针的初始位置。
547          g_munite.drawString("",munite_a,munite_b);
548          int i=munite;
549          while(true)
550           {     //第一次,过60-second秒就前进一分钟,以后每过60秒前进一分钟。
551                 try{分针.sleep(1000*60-second*1000);second=0;
552                  Color c=getBackground();g_munite.setColor(c);
553                  //用背景色清除前一分钟的分针:
554                  g_munite.drawLine(0,0,munite_a,munite_b);
555g_munite.drawString("",munite_a,munite_b);
556                  //如果这时分针与时针重合,恢复时针的显示:
557                   if((hour_a==munite_a)&&(hour_b==munite_b))
558                   { g_hour.drawLine(0,0,hour_a,hour_b);
559                     g_hour.drawString("",hour_a,hour_b);
560                   }
 
561                 }

562            catch(InterruptedException e)
563                 {return;
564                 }
 
565                //分针向前走一个单位:
566                munite_a=(int)point_x[(i+1)%60];
567                munite_b=(int)point_y[(i+1)%60];//分针每分钟走6度(一个单位格)。
568                g_munite.setColor(Color.blue);
569                g_munite.drawLine(0,0,munite_a,munite_b);//绘制新的分针。
570                g_munite.drawString("",munite_a,munite_b);
571                i++;   second=0;         
572           }

573      }
 
574    if(Thread.currentThread()==时针)
575      int h=hour%12;
576        hour_a=(int)point_x[h*5+munite/12];
577hour_b=(int)point_y[h*5+munite/12];  
578        int i= h*5+munite/12;      
579        g_hour.drawLine(0,0,hour_a,hour_b);
580        g_hour.drawString("",hour_a,hour_b);
581      while(true)
582      {//第一次,过12-munite%12分钟就前进一个刻度,以后每过12分钟前进一个刻度.
583try{
584时针.sleep(1000*60*12-1000*60*(munite%12)-second*1000);munite=0;
585          Color c=getBackground();g_hour.setColor(c);
586          g_hour.drawLine(0,0,hour_a,hour_b);// 用背景色清除前12分钟时的时针. 
587          g_hour.drawString("",hour_a,hour_b);
588          }

589        catch(InterruptedException e)
590                {return;
591                }
 
592       hour_a=(int)point_x[(i+1)%60];
593       hour_b=(int)point_y[(i+1)%60];//时针每12分走6度(一个单位格)
594       g_hour.setColor(Color.cyan);
595       g_hour.drawLine(0,0,hour_a,hour_b);//绘制新的时针.
596       g_hour.drawString("",hour_a,hour_b);
597       i++; munite=0;
598       }

599     }

600  }
   
601}

602
posted @ 2005-05-27 09:40  Rookie.Zhang  阅读(906)  评论(1编辑  收藏  举报