三个线程轮流打印1-100

2020-06-19  本文已影响0人  Djbfifjd

一、synchronized关键字实现

public class MyThread1 implements Runnable {
    private static Object lock = new Object();
    private static int count;
    private int no;
    public MyThread1(int no) {
        this.no = no;
    }
    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                if (count > 100) {
                    break;
                }
                if (count % 3 == this.no) {
                    System.out.println(this.no + "--->" + count);
                    count++;
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notifyAll();
            }
        }
    }
}

二、ReentrantLock实现

public class MyThread2 implements Runnable {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static int count;
    private int no;
    public MyThread2(int no) {
        this.no = no;
    }
    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (count > 100) {
                break;
            } else {
                if (count % 3 == this.no) {
                    System.out.println(this.no + "-->" + count);
                    count++;
                } else {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            condition.signalAll();
            lock.unlock();
        }
    }
}

三、main函数

public class ThreadTest {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new MyThread2(0));
        Thread t2 = new Thread(new MyThread2(1));
        Thread t3 = new Thread(new MyThread2(2));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
    }
}
上一篇下一篇

猜你喜欢

热点阅读