2010-05-23 14:48 Java(6)线程暂停、恢复

18.线程暂停、恢复
*public class Object
     void notify() 唤醒在此对象监视器上等待的单个线程
     void notifyAll() 唤醒在此对象监视器上等待的所有线程。
     void wait() 导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
用wait(),notify()方法来控制线程.
*实例
01 /**
02 * 线程暂停,恢复
03 *
04 * @author Administrator
05 *
06 */
07 public class ThreadSuspend implements Runnable {
08
09   private String name;
10   private Thread t;
11
12   private boolean suspendFlag = false;// 控制线程的执行
13
14   public ThreadSuspend(String name) {
15     this.name = name;
16     t = new Thread(this, name);
17     System.out.println("new Thread: " + t);
18     t.start();
19   }
20
21   public void run() {
22     try {
23       for (int i = 0; i < 6; i++) {
24         System.out.println(name + ": " + i);
25         Thread.sleep(500);
26         synchronized (this) {
27           while (suspendFlag)
28             wait();
29         }
30       }
31     } catch (InterruptedException e) {
32       e.printStackTrace();
33     }
34     System.out.println(name + " exited");
35   }
36
37   /**
38    * 线程暂停
39    */
40   public void setSuspendFlag() {
41     this.suspendFlag = true;
42   }
43
44   /**
45    * 唤醒线程
46    */
47   public synchronized void setResume() {
48     this.suspendFlag = false;
49     notify();
50   }
51
52   /**
53    * 返回线程名
54    *
55    * @return name
56    */
57   public String getName() {
58     return name;
59   }
60
61   public Thread getT() {
62     return t;
63   }
64 }



01 /**
02    * 测试 ThreadSuspend类
03    */
04   public void testSuspend() {
05     ThreadSuspend one = new ThreadSuspend("one");
06     ThreadSuspend two = new ThreadSuspend("two");
07     try {
08       Thread.sleep(1000);
09       
10       System.out.println("suspending thread "+one.getName());
11       one.setSuspendFlag();
12       Thread.sleep(1000);
13       System.out.println("resuming thread "+one.getName());
14       one.setResume();
15       
16       System.out.println("suspending thread "+two.getName());
17       two.setSuspendFlag();
18       Thread.sleep(1000);
19       System.out.println("resuming thread "+two.getName());
20       two.setResume();
21       
22       one.getT().join();
23       two.getT().join();
24       
25     } catch (InterruptedException e) {
26       e.printStackTrace();
27     }
28     System.out.println("main thread exit");
29   }

测试结果:new Thread: Thread[one,5,main]
new Thread: Thread[two,5,main]
two: 0
one: 0
one: 1
two: 1
suspending thread one
two: 2
two: 3
resuming thread one
suspending thread two
two: 4
one: 2
one: 3
one: 4
resuming thread two
two: 5
one: 5
two exited
one exited
main thread exit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值