package com.example.socket;
public class test {
private static Object LOCK = new Object();
private static boolean flag = false;
class A extends Thread{
public void run() {
for (int c = 0; c <= 10; c++) {
synchronized (LOCK) {
System.out.println("a");
if(!flag){
flag = true;
LOCK.notify(); //在这里虽然唤醒了另一个线程b,但锁并没有释放
try {
LOCK.wait();//在wait后的瞬间线程b得到锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class B extends Thread{
public void run() {
for (int c = 0; c <= 10; c++) {
synchronized (LOCK) {
System.out.println("b");
if(flag){
flag = false;
LOCK.notify();
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
test x = new test();
x.new A().start();
x.new B().start();
}
}
参考自http://jeasonjack.iteye.com/blog/1844512