两个线程交替执行输出,一个数字1-10,一个字符a-e ,打印出来12a34b56c78d910e

两个线程交替执行输出,一个数字1-10,一个字符a-e ,打印出来12a34b56c78d910e

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : 孤傲然
 * @description : 两个线程,一个数字1-10,一个字符a-e ,打印出来12a34b56c78d910e
 * @date :2020/7/18 23:03
 */
public class ThreadDemo {

    public static volatile boolean flag = false;

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition numCondition = lock.newCondition();
        Condition strCondition = lock.newCondition();
        new ThreadStr(lock,numCondition,strCondition).start();
        new ThreadNum(lock,numCondition,strCondition).start();
    }

    static class ThreadNum extends Thread {
        private Lock lock;
        private Condition numCondition;
        private Condition strCondition;

        public ThreadNum(Lock lock, Condition numCondition, Condition strCondition) {
            this.lock = lock;
            this.numCondition = numCondition;
            this.strCondition = strCondition;
        }

        @Override
        public void run() {
            lock.lock();
            flag = true;
            try {
                for (int i = 1; i < 11; i++) {
                    System.out.print(i);
                    if(i%2==0){
                        strCondition.signal();
                        numCondition.await();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    static class ThreadStr extends Thread {
        private Lock lock;
        private Condition numCondition;
        private Condition strCondition;

        public ThreadStr(Lock lock, Condition numCondition, Condition strCondition) {
            this.lock = lock;
            this.numCondition = numCondition;
            this.strCondition = strCondition;
        }

        @Override
        public void run() {
            while (!flag) {
            }
            lock.lock();
            try {
                for (int i = 97; i < 102; i++) {
                    System.out.print((char) i);
                    numCondition.signal();
                    // 如果是e ,说明执行到最后了, 不在阻塞了
                    if(i!=101) {
                        strCondition.await();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}

你可能感兴趣的:(两个线程交替执行输出,一个数字1-10,一个字符a-e ,打印出来12a34b56c78d910e)