18.线程暂停、恢复
测试结果: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
*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