代码功能:子线程每次循环5次,主线程每次循环10次,子线程先执行,如此交替执行50次。
分析:子线程执行过程中不能被主线程打断,主线程执行过程中不能被子线程打断,因此需要进行互斥,需要交替执行,因此需要进行同步。互斥可以利用synchronized,同步可以采用wait和notify
代码如下:
public class SynchronousTest {
public static void main(String[] args) {
final Business business = new Business();
Thread sub = new Thread() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
business.sub(i);
Thread.yield();
}
}
};
sub.start();
for (int i = 0; i < 50; i++) {
business.main(i);
Thread.yield();
}
}
}
class Business {
boolean shouldSubRun = true;
public synchronized void sub(int i) {
while(!shouldSubRun) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j < 5; j++) {
System.out.println("loop-" + i + " Sub Thread: " + j);
}
shouldSubRun = false;
this.notify();
}
public synchronized void main(int i) {
while(shouldSubRun) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j < 10; j++) {
System.out.println("loop-" + i + " Main Thread: " + j);
}
shouldSubRun = true;
this.notify();
}
}
——致敬张孝祥老师