// 面试题,子线程2执行10次子线程2执行20次 与主线程100次来回循环执行50次 public class interview { public static void main(String[] args) { final Business b = new Business(); new Thread(new Runnable(){ @Override public void run() { for (int i = 1; i <= 50; i++) { b.sub2(i); } } }).start(); new Thread(new Runnable(){ @Override public void run() { for (int i = 1; i <= 50; i++) { b.sub3(i); } } }).start(); for (int i = 1; i <= 50; i++) { b.main(i); } } } class Business{ private int order=1; Lock lock = new ReentrantLock(); Condition con1 = lock.newCondition(); Condition con2 = lock.newCondition(); Condition con3 = lock.newCondition(); public void sub2(int i){ lock.lock(); try { while (order != 2) { try { con2.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("sub2 Thread is sequence of " + j + "..lamp of " + i); } System.out.println("/.................."); order = 3; con3.signal(); } finally{ lock.unlock(); } } public void sub3(int i){ lock.lock(); try { while (order != 3) { try { con3.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 20; j++) { System.out.println("sub3 Thread is sequence of " + j + "..lamp of " + i); } System.out.println("/.................."); order = 1; con1.signal(); } finally{ lock.unlock(); } } public void main(int i){ lock.lock(); try { while (order != 1) { try { con1.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 100; j++) { System.out.println("main Thread is sequence of " + j + "..lamp of " + i); } order = 2; System.out.println("........................"); con2.signal(); } finally { lock.unlock(); } } }
面试题,子线程10次子线程2执行20次与主线程100次来回循环执行50次
时间: 2024-10-05 09:17:11