java怎么拦截某个对象
246
2022-08-23
java: 三个线程交替打印A、B、C
package com.example.app;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;import java.util.concurrent.locks.Condition;public class ThreadTest { private static Lock lock = new ReentrantLock(true); private static Condition condition1 = lock.newCondition(); private static Condition condition2 = lock.newCondition(); private static Condition condition3 = lock.newCondition(); private static String str = "A"; public static void main(String[] args) { Thread t1=new Thread(new Runnable() { @Override public void run() { while (true){ try { printA(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread t2=new Thread(new Runnable() { @Override public void run() { while (true){ try { printB(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { while (true){ try { printC(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t1.start(); t2.start(); t3.start(); } public static void printA() throws InterruptedException { lock.lock(); try{ while(!str.equals("A")){ condition1.await(); } System.out.println("A"); str = "B"; condition2.signalAll(); }finally { lock.unlock(); } } public static void printB() throws InterruptedException { lock.lock(); try{ while(!str.equals("B")){ condition2.await(); } System.out.println("B"); str = "C"; condition3.signalAll(); }finally { lock.unlock(); } } public static void printC() throws InterruptedException { lock.lock(); try{ while(!str.equals("C")){ condition3.await(); } System.out.println("C"); str = "A"; condition1.signalAll(); }finally { lock.unlock(); } }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~