/**
* 子线程循环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();
}
}
}