现有如下需求:
子线程10次与主线程100次,循环执行50次。
实现方法:
1、将子线程和主线程中要同步的方法进行封装,加上同步关键字实现同步;
2、两个线程间隔运行,添加一个标记变量进行比较以实现相互通信
package tradition;
/**
* 传统线程间通信,wait和notify
*/
public class TraditionalThreadCommunication {
/**
* 主方法
* @param args
*/
public static void main(String[] args) {
final Business business = new Business();
//子线程
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 1; i < 50; i ++) {
business.sub(i);
}
}
}).start();
//主线程
for(int i = 1; i < 50; i ++) {
business.main(i);
}
}
}
class Business {
private boolean bShouldSub = true;
/**
* 代表子线程的方法
* @param i
*/
public synchronized void sub(int i){
//如果为false,则等待
while(!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果bShouldSub为true则执行
for(int j = 1; j <= 10; j ++){
System.out.println("sub thread sequence of "
+ i +", loop of " + j);
}
//执行完之后将bShouldSub设置为false
bShouldSub = false;
this.notify();
}
/**
* 代表主线程的方法
* @param i
*/
public synchronized void main(int i){
while(bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j = 1; j <= 100; j ++){
System.out.println("main thread sequence of " + i
+", loop of " + j);
}
bShouldSub = true;
this.notify();
}
}
注意:wait()和notify()方法必须要在synchronized代码块中写。
参考视频:《Java多线程与并发库高级应用》