程序题:两个线程交叉打印0-1000,一个线程奇数,一个线程偶数

如题

public class PrintNumThreadTest {


    public static void main(String[] args) {
        PrintNumOpt printNumOpt = new PrintNumOpt();
        new Thread(() -> printNumOpt.print0()).start();
        new Thread(() -> printNumOpt.print1()).start();
    }
}


class PrintNumOpt {

    int num = 0;
    int opt = 0;
    int maxNum = 100;


    ReentrantLock lock = new ReentrantLock();
    /**
     * 偶数
     */

    Condition condition0 = lock.newCondition();
    /**
     * 奇数
     */
    Condition condition1 = lock.newCondition();

    public void print0() {
        while (this.opt == 0) {
            lock.lock();
            try {
                for (; num < maxNum; num++) {
                    if (num % 2 == 0) {
                        System.out.println("偶数:" + num);
                        this.opt = 1;
                        condition1.signal();
                        condition0.await();
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public void print1() {
        while (this.opt == 1) {
            lock.lock();
            try {
                for (; num < maxNum; num++) {
                    if (num % 2 == 1) {
                        System.out.println("奇数:" + num);
                        this.opt = 0;
                        condition0.signal();
                        condition1.await();


                    }
                }


            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


}

你可能感兴趣的:(程序题:两个线程交叉打印0-1000,一个线程奇数,一个线程偶数)