Java线程wait()与notify()

本文介绍了一道经典的线程同步面试题,通过两个线程A和B的交替打印实现来展示如何使用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();
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值