三个线程轮流打印1-100(两种实现方式)

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

synchronized关键字实现

class MyThread1 implements Runnable{

    private static Object lock = new Object();

    private static int count =0 ;

    int no;

    public MyThread(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实现

class MyThread2 implements Runnable{

    private int no;

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition condition = lock.newCondition();

    private static int count;

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

你可能感兴趣的:(三个线程轮流打印1-100(两种实现方式))