线程打印交替

时间:2017-04-04 19:28:08

标签: java multithreading

我正在尝试使用ReentrantLock在两个线程之间进行通信,因此输出将依次为A,然后是B.

这是我的计划:

public class ThreadPrinter5 {

    private final ReentrantLock lock = new ReentrantLock();
    private int count = 0;

     //Locking using Lock and ReentrantLock
     public int getCount() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " gets Count: " + count);
            return count++;
        } finally {
            lock.unlock();
        }
     }

    public static void main(String args[]) {
        final ThreadPrinter5 counter = new ThreadPrinter5();
        Thread t1 = new Thread("A") {

            @Override
            public void run() {
                while (counter.getCount() < 6) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();                    }
                }
            }
        };

        Thread t2 = new Thread("B") {

            @Override
            public void run() {
                while (counter.getCount() < 6) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };

        t1.start();
        t2.start();

    }
}

这是输出:

A gets Count: 0
B gets Count: 1
A gets Count: 2
B gets Count: 3
B gets Count: 4
A gets Count: 5
A gets Count: 6
B gets Count: 7

这里A重复两次,用于计数5&amp; 6。

我们如何确保使用ReentrantLock

按顺序打印A然后B?

0 个答案:

没有答案