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

来源:互联网 发布:少女时代内部矛盾知乎 编辑:程序博客网 时间:2024/05/22 00:34

启动三个线程,一个线程专门打印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
原创粉丝点击