public class Ex5 { AtomicInteger num=new AtomicInteger(0); ReentrantLock lock=new ReentrantLock(true); void work(){ String n=Thread.currentThread().getName(); while (true){ lock.lock(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("%s%d ",n,num.incrementAndGet()); if ("C".equals(n)){ System.out.println(); } lock.unlock(); } } public static void main(String[] args) { var t=new Ex5(); new Thread(t::work,"A").start(); new Thread(t::work,"B").start(); new Thread(t::work,"C").start(); } }运行结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)