线程间通过锁对象进行同步,将锁加在多个线程共同访问的资源上,实现多个线程的同步
线程间 可以通过 notify(),notifyAll(),wait()方法进行调度,wait()必须用在同步代码块或同步方法里,锁对象调用wait()后,释放同步方法锁,给其他具有同等优先级,或者更高优先级的线程执行,
public class TraditionalThreadCommunication {
public static void main(String[] args) {
final Bussiness bussiness = new Bussiness();
new Thread(new Runnable() {
@Override
public void run() {
for (int m = 0; m < 50; m++) {
bussiness.sub(m);
}
}
}).start();
for (int m = 0; m < 50; m++) {
bussiness.main(m);
}
}
}
class Bussiness {
private boolean bShouldSub = true;
public synchronized void main(int m) {
//为什么不用if,而用while
//防止伪同步,有时候线程wait()了也自动唤醒会执行,这时while判断,
while (!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 100; i++) {
System.out.println("main thread sequence of" + i+"of loop "+m);
}
bShouldSub = false;
this.notify();
}
public synchronized void sub(int m) {
while (bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("sub thread sequence of" + i+ "of loop "+m);
}
bShouldSub = true;
this.notify();
}
}