1.synchronized/wait/notify
package javamultithread; import java.util.logging.Level;
import java.util.logging.Logger; /**
*
* @author Tina
*/
public class Thread1 implements Runnable { private final Object current;
private final Object next;
private String name; public Thread1(String name, Object current, Object next) {
this.name = name;
this.current = current;
this.next = next;
} @Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (current) {
synchronized (next) {
System.out.print(name);
if (name.equalsIgnoreCase("C")) {
System.out.println();
}
next.notify();
}
if (i < 9) {
try {
current.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
} public static void main(String[] args) {
try {
// TODO code application logic here
Object o1 = new Object();
Object o2 = new Object();
Object o3 = new Object();
Thread th1 = new Thread(new Thread1("A", o1, o2));
Thread th2 = new Thread(new Thread1("B", o2, o3));
Thread th3 = new Thread(new Thread1("C", o3, o1));
th1.start();
Thread.sleep(10);
th2.start();
Thread.sleep(10);
th3.start();
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(JavaMultiThread.class
.getName()).log(Level.SEVERE, null, ex);
} }
}
执行结果:
run:
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
成功构建 (总时间: 秒)