设为首页 加入收藏

TOP

Java线程wait()与notify()
2014-11-24 14:16:47 来源: 作者: 【 】 浏览:1
Tags:Java 线程 wait notify

实现一道经典的面试题


首先线程A打印10次,然后给线程B打印5次,然后再给线程A打印10次,然后再给B打印5次,如此循环10次


分析:其实这道题目也就是考察线程的同步以及wait()、notify()的使用。具体实现如下:


public class ThreadWait {


/**
* @param args
*/
public static void main(String[] args) {
final Temp temp = new Temp();
new Thread(){
public void run(){
for (int i = 1; i <= 5; i++) {
try {
temp.methodA(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();

new Thread(){
public void run(){
for (int i = 1; i <= 5; i++) {
try {
temp.methodB(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();

}


}


class Temp{

private boolean flag = true ;//互斥变量

public synchronized void methodA(int i) throws InterruptedException{
if(!flag){
this.wait();
}
for (int j = 1; j <= 10; j++) {
System.out.println("methodA "+j+"------"+i);
}
flag = false ;
this.notify();
}

public synchronized void methodB(int i) throws InterruptedException{
if(flag){
this.wait();
}
for (int j = 1; j <= 5; j++) {
System.out.println("methodB "+j+"------"+i);
}
flag = true ;
this.notify();
}

}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Apk文件破解可见源码 下一篇Android matrix 控制图片的旋转、..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: