面试题(三个线程ABC,将名字按顺序输出到控制台,如ABCABC.....)

题目:有三个线程,名字为A,B,C,现在需要将它们的名字有序的打印在控制台上,顺序为ABCABC… 【面试题(三个线程ABC,将名字按顺序输出到控制台,如ABCABC.....)】思路:
因为要控制某个线程的执行顺序,所以采用lock+condition+ewait+signalAll的方式
执行线程方法的类:

class ABC {private int num = 1; Lock lock = new ReentrantLock(); // 每一个Condition控制一个线程,让它们有序的执行 Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Condition condition3 = lock.newCondition(); publicvoid lockA(){ lock.lock(); try { if(num!=1){ try { condition1.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()); num = 2; condition2.signalAll(); } finally { lock.unlock(); } }publicvoid lockB(){ lock.lock(); try { if(num!=2){ try { condition2.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()); num = 3; condition3.signalAll(); } finally { lock.unlock(); } }publicvoid lockC(){ lock.lock(); try { if(num!=3){ try { condition3.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()); num = 1; condition1.signalAll(); }finally { lock.unlock(); } } }

线程类:
class JymTestDemo implements Runnable{private ABC abc = new ABC(); public void run() { if(Thread.currentThread().getName().equals("A")){ for(int i =0; i<10; i++){ abc.lockA(); } } else if (Thread.currentThread().getName().equals("B")){ for(int i =0; i<10; i++){ abc.lockB(); } } else if (Thread.currentThread().getName().equals("C")){ for(int i =0; i<10; i++){ abc.lockC(); } } }}

测试方法:
public class JymTest { public static void main(String[] args) { JymTestDemo jymTestDemo = new JymTestDemo(); new Thread(jymTestDemo,"A").start(); new Thread(jymTestDemo,"B").start(); new Thread(jymTestDemo,"C").start(); } }

执行结果:
面试题(三个线程ABC,将名字按顺序输出到控制台,如ABCABC.....)
文章图片

学习年限不足,知识过浅,说的不对请见谅。 世界上有10种人,一种是懂二进制的,一种是不懂二进制的。

    推荐阅读