面试题 -- 两个线程交替运行

业务场景:应付面试。

实战价值:代码过于复杂难以维护,实际生产不可能手搓线程,执行这种操作。

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

/**
 * @author Mr.css
 * @version 2022-08-03 16:36
 */
public class AlternatePrint {

    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition thread1Condition = lock.newCondition();
    private static final Condition thread2Condition = lock.newCondition();
	// isThread1Turn 用于指示当前是否轮到 Thread1 打印。
    private static boolean isThread1Turn = true;

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Task("Thread1", 1, 10), "Thread1");
        Thread thread2 = new Thread(new Task("Thread2", 2, 10), "Thread2");

        thread1.start();
        thread2.start();
    }

    static class Task implements Runnable {
        private final String name;
        private final int start;
        private final int end;

        public Task(String name, int start, int end) {
            this.name = name;
            this.start = start;
            this.end = end;
        }

        @Override
        public void run() {
            for (int i = start; i <= end; i++) {
                lock.lock();
                try {
					// 这一行代码有点乱,代码含义就是:轮到一个线程执行时,将另一个线程暂停
                    while ((isThread1Turn && !name.equals("Thread1")) || (!isThread1Turn && !name.equals("Thread2"))) {
                        if (name.equals("Thread1")) {
                            thread1Condition.await();
                        } else {
                            thread2Condition.await();
                        }
                    }

                    System.out.println(name + ": " + i);

                    if (name.equals("Thread1")) {
                        isThread1Turn = false;
                        thread2Condition.signal();
                    } else {
                        isThread1Turn = true;
                        thread1Condition.signal();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}

posted on 2017-07-27 20:08  疯狂的妞妞  阅读(152)  评论(0)    收藏  举报

导航