子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次。摘自张孝祥老师线程视频源码
package test;
public class Test {
// 子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次
public static void main(String[] args) {
new Test().init();
}
private void init() {
final Business business = new Business();
new Thread() {
public void run() {
for (int i = 1; i <= 10; i++) {
business.subdo();// 子线程
}
};
}.start();
for (int i = 1; i <= 10; i++) {
// business.subdo();// 子线程
business.maindo();
}
}
class Business {
private boolean isShouldSub = true;
public void subdo() {
synchronized (Test.class) {
if (!isShouldSub) {// 如果不该子线程执行
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName()
+ " running .." + " " + i + "次");
}
isShouldSub=false;
Test.class.notifyAll();
}
}
public void maindo() {
synchronized (Test.class) {
if (isShouldSub) {
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 20; i++) {
System.out.println(Thread.currentThread().getName()
+ " running .." + " " + i + "次");
}
isShouldSub=true;
Test.class.notifyAll();
}
}
}
}
本文详细介绍了如何在一个程序中实现子线程与主线程的交替循环操作,通过实例展示了同步机制的运用,以及如何在并发环境中确保数据的一致性和正确执行流程。
670

被折叠的 条评论
为什么被折叠?



