笔试题:编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
2017年03月21日 19:25:02
阅读数:712
这是最近笔试遇到一个多线程题,当时没有做出来,后来经过查找后,找到两种写法。
方法一:利用Lock和Condition来实现,代码如下
public class PrintABC {undefined
private String printFlag = "A";
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
public void printA(){undefined
lock.lock();
try {undefined
if(!printFlag.equals("A")){//1.判断是否到了状态 是-继续往下走 否-让当前线程处于等待状态
c1.await();//造成当前线程在接到信号或被中断之前一直处于等待状态。
}
System.out.println(Thread.currentThread().getName());//2.输出
printFlag = "B"; //3.将后续状态改为输出B
c2.signal();//4.唤醒输出B的线程
} catch (InterruptedException e) {undefined
e.printStackTrace();
}finally{undefined
lock.unlock();
}
}
public void printB(){undefined
lock.lock();
try {undefined
if(!printFlag.equals("B")){undefined
c2.await();
}
System.out.println(Thread.currentThread().getName());
printFlag = "C";
c3.signal();
} catch (InterruptedException e) {undefined
e.printStackTrace();
}finally{undefined
lock.unlock();
}
}
public void printC(){undefined
lock.lock();
try {undefined
if(!printFlag.equals("C")){undefined
c3.await();
}
System.out.println(Thread.currentThread().getName());
printFlag = "A";
c1.signal();
} catch (InterruptedException e) {undefined
e.printStackTrace();
}
}
//测试类
public static void main(String[] args) {undefined
final PrintABC test = new PrintABC();
new Thread(new Runnable() { //创建名称为A的线程并启动
public void run() {undefined
for(int x = 0;x<10;x++){//调用十次输出方法
test.printA();
}
}},"A").start();
new Thread(new Runnable() { //创建名称为B的线程并启动
public void run() {undefined
for(int x = 0;x<10;x++){undefined
test.printB();
}
}},"B").start();
new Thread(new Runnable() { //创建名称为C的线程并启动
public void run() {undefined
for(int x = 0;x<10;x++){undefined
test.printC();
}
}},"C").start();
}
}