标签:semaphore 任务 唤醒 sem oid 线程等待 start tno 共享
线程间通信常用方式如下:
l 休眠唤醒方式:
Object的wait、notify、notifyAll
Condition的await、signal、signalAll
l CountDownLatch:用于某个线程A等待若干个其他线程执行完之后,它才执行
l CyclicBarrier:一组线程等待至某个状态之后再全部同时执行
l Semaphore:用于控制对某组资源的访问权限
Object的wait、notify、notifyAll
public class WaitNotifyRunnable{ private Object obj = new Object(); private Integer i=0; public void odd() { while(i<10){ synchronized (obj){ if(i%2 == 1){ System.out.println("奇数:"+i); i++; obj.notify(); } else { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
public void even(){ while(i<10){ synchronized (obj){ if(i%2 == 0){ System.out.println("偶数:"+i); i++; obj.notify(); } else { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args){ final WaitNotifyRunnable runnable = new WaitNotifyRunnable(); Thread t1 = new Thread(new Runnable() { public void run() { runnable.odd(); } }, "偶数线程"); Thread t2 = new Thread(new Runnable() { public void run() { runnable.even(); } }, "奇数线程"); t1.start(); t2.start(); } }
Condition的await、signal、signalAll
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class WaitNotifyRunnable{ private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private Integer i=0; public void odd() { while(i<10){ lock.lock(); try{ if(i%2 == 1){ System.out.println("奇数:"+i); i++; condition.signal(); } else { condition.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } public void even(){ while(i<10){ lock.lock(); try{ if(i%2 == 0){ System.out.println("偶数:"+i); i++; condition.signal(); } else { condition.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } public static void main(String[] args){ final WaitNotifyRunnable runnable = new WaitNotifyRunnable(); Thread t1 = new Thread(new Runnable() { public void run() { runnable.odd(); } }, "偶数线程"); Thread t2 = new Thread(new Runnable() { public void run() { runnable.even(); } }, "奇数线程"); t1.start(); t2.start(); } }
Object和Condition休眠唤醒区别
l object wait()必须在synchronized(同步锁)下使用,
l object wait()必须要通过Nodify()方法进行唤醒
l condition await() 必须和Lock(互斥锁/共享锁)配合使用
l condition await() 必须通过 signal() 方法进行唤醒
CountDownLatch这个类能够使一个线程等待其他线程完成各自的工作后再执行。
CountDownLatch是通过一个计数器来实现的,计数器的初始值为线程的数量
每当一个线程完成了自己的任务后,计数器的值就会减1。当计数器值到达0时,它表示所有的线程已经完成了任务,然后在闭锁上等待的线程
标签:semaphore 任务 唤醒 sem oid 线程等待 start tno 共享
原文地址:https://www.cnblogs.com/sunliyuan/p/12188289.html