1、五个线程编号1、2、3、4、5,每个线程的执行完成时间不确定,要求按照排号顺序输出各个线程的结果,并且不能等所有线程执行完毕再排序输出,比如线程2先于线程1执行完了此时还不能输出。要等线程1输出完之后才能输出,其他线程以此类推
方案一、利用所得传递,创建五把锁 lock 1、2、3、4、5,线程1创建的时候lock1.lock 执行完毕后lock1.unlock 当线程2创建时候lock2.lock,输出方法里调用lock1.lock,输出完成之后执行lock1.unlock,再执行lock2.unlock,目的就是线程1把lock1释放之后 线程2才能获取到lock1然后才可以输出,后边的线程以此类推:
public void test() { ReentrantLock lock1 = new ReentrantLock(); ReentrantLock lock2 = new ReentrantLock(); ReentrantLock lock3 = new ReentrantLock(); ReentrantLock lock4 = new ReentrantLock(); ReentrantLock lock5 = new ReentrantLock(); Thread1 thread1 = new Thread1(lock1); Thread1 thread2 = new Thread2(lock1, lock2); Thread1 thread3 = new Thread3(lock2, lock3); Thread1 thread4 = new Thread4(lock3, lock4); Thread1 thread5 = new Thread5(lock4, lock5); }
class Thread1 extends Thread { ReentrantLock lock1; Thread1(ReentrantLock lock1) { this.lock1 = lock1; this.lock1.lock(); } void doSomeThing() { } private void doPrint() { System.out.println("result1"); lock1.unlock(); } @Override public void run() { super.run(); doSomeThing(); doPrint(); } }
class Thread2 extends Thread { ReentrantLock lock1; ReentrantLock lock2; Thread2(ReentrantLock lock1, ReentrantLock lock2) { this.lock1 = lock1; this.lock2 = lock2; this.lock2.lock(); } void doSomeThing() { } private void doPrint() { lock1.lock(); System.out.println("result1"); lock1.unlock(); lock2.unlock(); } @Override public void run() { super.run(); doSomeThing(); doPrint(); } }
方案二、利用线程的join方法,在本线程输出时使用前一个线程的join方法等待前一个执行完毕
public void testX() { ThreadX thread1 = new ThreadX(null); ThreadX thread2 = new ThreadX(thread1); ThreadX thread3 = new ThreadX(thread2); ThreadX thread4 = new ThreadX(thread3); ThreadX thread5 = new ThreadX(thread4); }
class ThreadX extends Thread { Thread threadPre; ThreadX(Thread threadPre) { this.threadPre = threadPre; } void doSomeThing() { } private void doPrint() { try { if (threadPre != null) { threadPre.join(); } System.out.println("result1"); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void run() { super.run(); doSomeThing(); doPrint(); } }
标签:void,ReentrantLock,---,lock1,线程,new,排序,ThreadX From: https://www.cnblogs.com/bimingcong/p/18259356