Java 多线程编程

1.synchronized/wait/notify

 1 package javamultithread;
 2 
 3 import java.util.logging.Level;
 4 import java.util.logging.Logger;
 5 
 6 /**
 7  *
 8  * @author Tina
 9  */
10 public class Thread1 implements Runnable {
11 
12     private final Object current;
13     private final Object next;
14     private String name;
15 
16     public Thread1(String name, Object current, Object next) {
17         this.name = name;
18         this.current = current;
19         this.next = next;
20     }
21 
22     @Override
23     public void run() {
24         for (int i = 0; i < 10; i++) {
25             synchronized (current) {
26                 synchronized (next) {
27                     System.out.print(name);
28                     if (name.equalsIgnoreCase("C")) {
29                         System.out.println();
30                     }
31                     next.notify();
32                 }
33                 if (i < 9) {
34                     try {
35                         current.wait();
36                     } catch (InterruptedException ex) {
37                         Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
38                     }
39                 }
40             }
41         }
42     }
43 
44     public static void main(String[] args) {
45         try {
46             // TODO code application logic here
47             Object o1 = new Object();
48             Object o2 = new Object();
49             Object o3 = new Object();
50             Thread th1 = new Thread(new Thread1("A", o1, o2));
51             Thread th2 = new Thread(new Thread1("B", o2, o3));
52             Thread th3 = new Thread(new Thread1("C", o3, o1));
53             th1.start();
54             Thread.sleep(10);
55             th2.start();
56             Thread.sleep(10);
57             th3.start();
58             Thread.sleep(10);
59         } catch (InterruptedException ex) {
60             Logger.getLogger(JavaMultiThread.class
61                     .getName()).log(Level.SEVERE, null, ex);
62         }
63 
64     }
65 }

执行结果:

run:
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
成功构建 (总时间: 0 秒)
原文地址:https://www.cnblogs.com/tt2015-sz/p/5866554.html