一道多线程互相通讯的面试题目

启动三个线程,一个线程专门打印A,一个线程专门打印B,一个线程专门打印C,要求循环10次,打印出ABCABCABCABCABCABCABCABCABCABC。


1 写出三个线程共享的类 Common,并有一个flag属性去控制顺序,代码如下:


package current;


public class Common {
private int flag=1;


public synchronized void printA( ){

while(flag!=1){
try {
this.wait();
} catch (InterruptedException e) {
 
e.printStackTrace();
}

}
flag=2;
System.out.print("A");
this.notifyAll();
 }




public synchronized void printB( ){

while(flag!=2){
try {
this.wait();
} catch (InterruptedException e) {
 
e.printStackTrace();
}

}
flag=3;
System.out.print("B");
this.notifyAll();
 }




public synchronized void printC( ){

while(flag!=3){
try {
this.wait();
} catch (InterruptedException e) {
 
e.printStackTrace();
}

}
flag=1;
System.out.print("C");
this.notifyAll();
 }


}


2依次编码三个线程类A,B,C


package current;


public class ThreadA extends Thread{


private Common  comm;



@Override
public void run() {
 for(int i=1;i<=10;i++){
 comm.printA();
 }
}




public ThreadA(Common comm) {
super();
this.comm = comm;
}


}


package current;


public class ThreadB extends Thread{


private Common  comm;
public ThreadB(Common comm) {
super();
this.comm = comm;
}

@Override
public void run() {
 for(int i=1;i<=10;i++){
 comm.printB();
 }
}


}


package current;


public class ThreadC extends Thread{


private Common  comm;


public ThreadC(Common comm) {
super();
this.comm = comm;
}
@Override
public void run() {
 for(int i=1;i<=10;i++){
 comm.printC();
 }
}


}



3编写测试类Test




package current;


public class Test {


/**
* @param args
*/
public static void main(String[] args) {
Common comm=new Common();
Thread  threadA=new ThreadA(comm);
Thread  threadB=new ThreadB(comm);
Thread  threadC=new ThreadC(comm);

threadA.start();
threadB.start();
threadC.start();
}


}


4 运行测试类即可得到正确结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值