java 兩個執行緒間隔列印1,2一共100次的騷操作

南郭竽發表於2018-06-26
package com.pycat.sample.print;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by cat on 2018/6/26.
 * print number
 * --- split print number 1,2 in two different thread
 */
public class PrintNumber {


    private final ReentrantReadWriteLock.WriteLock mLock;
    private final Condition condition1;
    private final Condition condition2;

    public PrintNumber() {
        this.mLock = new ReentrantReadWriteLock().writeLock();
        condition1 = mLock.newCondition();
        condition2 = mLock.newCondition();
    }

    private AtomicInteger count = new AtomicInteger(0);

    public void print1() {

        while (count.get() < 100) {
            try {
                mLock.lock();
                System.out.println(Thread.currentThread().getName() + ":" + 1 + "   " + count);
                count.set(count.get() + 1);
                condition2.signalAll();
                condition1.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mLock.unlock();
            }
        }
        System.out.println("end PRINT 111111111111111111111");
        mLock.lock();
        condition2.signalAll();
        condition1.signalAll();
        mLock.unlock();
    }

    public void print2() {

        while (count.get() < 100) {
            try {
                mLock.lock();
                System.out.println(Thread.currentThread().getName() + ":" + 2 + "  xxx " + count);
                count.set(count.get() + 1);
                condition1.signalAll();
                condition2.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mLock.unlock();
            }
        }
        System.out.println("end PRINT 222222222222222222222222");
        mLock.lock();
        condition1.signalAll();
        condition2.signalAll();
        mLock.unlock();
    }

}

呼叫:

package com.pycat.sample;

import com.pycat.sample.print.PrintNumber;

public class Main {

    public static void main(String[] args) {
        // write your code here
        System.out.println("hello world");

        PrintNumber number = new PrintNumber();
        new Thread(number::print1).start();
        new Thread(number::print2).start();
    }

}

大體實現就是這樣吧,反正思路就是:1列印了一次後,立即喚醒2,並讓自己等待;2和1邏輯相同。

然後需要注意一個細節就是最後,100次到了,不需要任何執行緒等待了,就把等待全部設定成喚醒。否則會導致程式一直不結束。

相關文章