Wellcom to my Blog for Javascript

java 多线程的唤醒

 1 package TestThread.ThreadSynchronized.TestInterruptedException;
 2 
 3 public class InterruptDemo {
 4     public static void main(String[] args) {
 5         TestWait t = new TestWait("线程1");
 6         TestWait t1 = new TestWait("线程2");
 7         Test te = new Test("线程3", t);
 8         t.start();
 9         t1.start();
10         te.start();
11     }
12 }
13 
14 class TestWait extends Thread {
15     String name;
16 
17     public TestWait(String name) {
18         super(name);
19         this.name = name;
20     }
21 
22     public synchronized void run() {
23         for (int i = 0; i < 5; i++) {
24             if (i == 4) {
25                 try {
26                     // 等待之后立即释放当前锁,并且进入等待池中等待唤醒
27                     // 当等待池中的线程被唤醒后,再次执行此语句之后的语句
28                     this.wait();
29                     System.out.println(Thread.currentThread().getName() + ":我还没有被执行到!");
30                 } catch (InterruptedException e) {
31                     e.printStackTrace();
32                 }
33             }
34             System.out.println(Thread.currentThread().getName() + ":当前的值为--->" + i);
35         }
36     }
37 }
38 
39 class Test extends Thread {
40     private TestWait testwait;
41     String name;
42 
43     public Test(String name, TestWait testwait) {
44         super(name);
45         this.name = name;
46         this.testwait = testwait;
47     }
48 
49     public void run() {
50         synchronized (testwait) {
51             testwait.notify();// 调用此方法后,指定的对象将被唤醒,唤醒之后将继续执行后面的操作
52         }
53     }
54 }

执行的结果为:

 

posted on 2017-03-24 09:31  温柔的鲨鱼  阅读(440)  评论(0编辑  收藏  举报

导航