Toy Program——线程同步。涉及wait(),notifyall(),runnable,toString
2016-05-20 14:17
330 查看
public class TestProducerConsumer { public static void main(String[] args) { SyncStack ss = new SyncStack(); Producer pd = new Producer(ss); Consumer cs = new Consumer(ss); new Thread(pd).start(); new Thread(pd).start(); new Thread(pd).start(); new Thread(cs).start(); new Thread(cs).start(); } } class SteamedBuns{ int id = 0; SteamedBuns(int id){ this.id = id; } public String toString(){ return "SteamedBuns: " + id; } } class Producer implements Runnable{ SyncStack sbsBuffer = null; Producer(SyncStack sbsBuffer){ this.sbsBuffer = sbsBuffer; } public void run(){ for(int i = 0; i < 20; i++){ SteamedBuns sbs = new SteamedBuns(i); sbsBuffer.putInto(sbs); System.out.println("+++Produced+++ " + sbs); try{ Thread.sleep(1000); }catch(InterruptedException ie){ ie.printStackTrace(); } } } } class Consumer implements Runnable{ SyncStack sbsBuffer = null; Consumer(SyncStack sbsBuffer){ this.sbsBuffer = sbsBuffer; } public void run(){ for(int i = 0; i < 20; i++){ SteamedBuns sbs = sbsBuffer.takeOut(); System.out.println("--Consumed-- " + sbs); try{ Thread.sleep(1000); }catch(InterruptedException ie){ ie.printStackTrace(); } } } } class SyncStack{ int index = 0; SteamedBuns[] arrSbs = new SteamedBuns[20]; public synchronized void putInto(SteamedBuns sbs){//线程锁定与唤醒 while(index == arrSbs.length){ try{ this.wait(); }catch(InterruptedException ie){ ie.printStackTrace(); } } this.notifyAll(); arrSbs[index] = sbs; index++; } public synchronized SteamedBuns takeOut(){//线程锁定与唤醒 while(index == 0){ try{ this.wait(); }catch(InterruptedException ie){ ie.printStackTrace(); } } this.notifyAll(); index--; return arrSbs[index]; } }
当线程需要阻塞式的等待时,则调用wait()。而wait()的同时,锁止权不由线程控制。
sleep()全程hold锁止权。
wait()搭配notify()和notifyAll()使用。
能用Interface的Runnable就不用class的Thread
相关文章推荐
- C#线程间不能调用剪切板的解决方法
- 在C#的类或结构中重写ToString方法的用法简介
- C#线程同步的三类情景分析
- C#获取进程或线程相关信息的方法
- 简单对比C#程序中的单线程与多线程设计
- C#停止线程的方法
- C#子线程更新UI控件的方法实例总结
- C#线程队列用法实例分析
- C++使用CriticalSection实现线程同步实例
- 基于C++实现的线程休眠代码
- VB读取线程、句柄及写入内存的API代码实例
- C#网络编程基础之进程和线程详解
- C#通过Semaphore类控制线程队列的方法
- C#多线程处理多个队列数据的方法
- C#实现线程安全的简易日志记录方法
- C#中线程同步对象的方法分析
- 深入多线程之:Wait与Pulse的使用详解
- ASP.NET线程相关配置
- 浅析linux环境下一个进程最多能有多少个线程
- 再谈JavaScript线程