您的位置:首页 > 其它

传统线程互斥技术----实现

2013-11-05 21:24 330 查看
//子线程循环10次,接着主线程循环100次,接着在子线程循环10次,接着再主线程循环100次
public class SynTest {
public static void main(String[] args) {
final Business b = new Business();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
b.sub();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
b.main();
}
}
}).start();
}
}
class Business {
private boolean flag = true;
public synchronized void sub() {
while (!flag) {// 用while防止假唤醒
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub thread:" + j);
}
flag = false;
this.notify();
}
public synchronized void main() {
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("main thread:" + j);
}
flag = true;
this.notify();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: