/**
* 子线程循环10次,主线程100次 如此循环50次;
*
* @time 上午11:45:17
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
/**
* 线程互吃
*/
class Business {
boolean isShouldSub = true;
// 主线程5
public synchronized void mani() {
if (isShouldSub) {
// 执行监视器的wait方法
try {
this.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程:" + Thread.currentThread().getName() + ":" + i);
}
}
isShouldSub = true;
this.notify();
}
// 子线程10
public synchronized void sub() {
if (isShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 10; i++) {
System.out.println("子线程:" + Thread.currentThread().getName() + ":" + i);
}
isShouldSub = false;
this.notify();
}
}
final Business business = new Business();
new Thread() {
public void run() {
while (true) {
business.sub();
}
}
}.start();
while (true) {
business.mani();
}
}
}
本文提供了一个Java多线程程序示例,演示了如何使用synchronized关键字实现主线程与子线程之间的交互。通过控制布尔变量来决定线程执行顺序,确保主线程执行5次后子线程执行10次,这种循环重复50次。

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



