演算法題---五個執行緒排序輸出

毕哥發表於2024-06-20

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();
        }
    }

相關文章