美文网首页
程序题:两个线程交叉打印0-1000,一个线程奇数,一个线程偶数

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

作者: Eve0 | 来源:发表于2021-04-12 22:06 被阅读0次

    如题

    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,一个线程奇数,一个线程偶数

          本文链接:https://www.haomeiwen.com/subject/vweflltx.html