1. 程式人生 > >兩個執行緒,輪流有序執行的兩種方法

兩個執行緒,輪流有序執行的兩種方法

要求:兩個執行緒的任務都是列印1到1000的資料,執行緒1列印一次後執行緒2繼續列印,實現輪流列印

方法1:使用interrupt()和sleep()協調使用,一個列印完成後sleep(),並且interrupt另一個執行緒的睡眠,同時讓自己睡眠,迴圈1000次即可

方法2:通過公共鎖object,配合wait()和notify()/notifyAll()方法,睡眠自己,喚醒另一執行緒,迴圈1000次

public class Test91 {

    private static Thread t1;
    private static Thread t2;
    private static Thread t3;
    private static List<Integer> integers;
    private static int i = 0;
    static final int MAX = 1000;
    private static final int ThreadCount = 2;

    public static void main(String... args) throws InterruptedException {
        integers = Collections.synchronizedList(new ArrayList<Integer>(ThreadCount * MAX));
        t1 = new MyThread1();
        t1.start();
        t2 = new MyThread2();
        t2.start();
    }

    private static void check() {
        System.out.println();
        System.out.println("---------------------");
        for (int i = 0; i < integers.size() - ThreadCount; i++) {
            if (i % 2 == 0) {
                if (!integers.get(i).equals(integers.get(i + ThreadCount - 1))) {
                    System.out.println(integers.get(i) + "和" + integers.get(i + 1) + "不相等");
                    break;
                }
            }
        }
    }

    static class MyThread1 extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < MAX; i++) {
                System.out.print(i + "\t");
                integers.add(i);
                runThread(t2, t1);
            }
        }
    }

    static class MyThread2 extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < MAX; i++) {
                System.out.print(i + "\t");
                integers.add(i);
                runThread(t1, t2);
            }
        }
    }

    private static Lock lock = new ReentrantLock();
    private static final Object object = new Object();

    static void runThread(Thread t1, Thread t2) {
//        synchronized (object) {
//            object.notifyAll();
//            try {
//                if (++i >= ThreadCount * MAX) {
//                    check();
//                } else {
//                    object.wait();
//                }
//
//            } catch (Exception e) {
//            }
//        }
        try {
            t1.interrupt();//讓另一個執行緒終端睡眠
            if (++i >= ThreadCount * MAX) {
                check();
            } else {
                Thread.sleep(1000);//讓當前執行緒睡眠
            }

        } catch (Exception e) {
        }
    }

兩種方法都在runThread方法內,註釋其一,就是一種方法;執行結果如下: