wait() 和notify重温

[align=center][size=medium][color=red]重温wait()和notify()[/color][/size][/align]

[size=medium][color=blue] 温故知新,接下来看看线程池。

同时启动3个线程A、B、C,A线程输出A 20次,B线程输出B 20次,C线程输出C 20次,要求输出结果为顺序输出A、B、C、A、B、C。。。[/color][/size]



class Agent{
public static int state = 1;

public synchronized void sayA() {
if(state != 1){
try {
super.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("A");
state = 2;
super.notify();
}
public synchronized void sayB() {
if(state != 2){
try {
super.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("B");
state = 3;
super.notify();
}
public synchronized void sayC() {
if(state != 3){
try {
super.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("C");
state = 1;
super.notify();
}
}

class A extends Thread{
Agent agent;
public A(Agent agent){
this.agent = agent;
}
public void run(){
for(int i=0;i<20;i++){
try {
Thread.sleep(200);
} catch (Exception e) {
}
agent.sayA();
}
}
}
class B extends Thread{
Agent agent;
public B(Agent agent){
this.agent = agent;
}
public void run(){
for(int i=0;i<20;i++){
try {
Thread.sleep(200);
} catch (Exception e) {
}
agent.sayB();
}
}
}
class C extends Thread{
Agent agent;
public C(Agent agent){
this.agent = agent;
}
public void run(){
for(int i=0;i<20;i++){
try {
Thread.sleep(200);
} catch (Exception e) {
}
agent.sayC();
}
}
}

public class TestWait {
public static void main(String[] args) {
Agent agent = new Agent();
new A(agent).start();
new B(agent).start();
new C(agent).start();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值