import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class ConditionDemo { static private ReentrantLock lock = new ReentrantLock(); static private Condition condition = lock.newCondition(); static AtomicInteger atomicInteger = new AtomicInteger(0); public static void main(String[] args) { new Thread(new Task()).start(); new Thread(new Task()).start(); } static class Task implements Runnable{ @Override public void run() { lock.lock(); try { while (atomicInteger.get() < 10){ System.out.println(Thread.currentThread().getName()+"_print:"+atomicInteger.getAndIncrement()); condition.signal(); try { // 防止一个线程执行结束,另一个线程没有被唤醒 condition.await(500, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { } } }finally { System.out.println(Thread.currentThread().getName()+"_end..."); lock.unlock(); } } } }
打印效果如下
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)