线程通信
来源:互联网 发布:淘宝开两家店 编辑:程序博客网 时间:2024/06/06 21:42
方法:wait():让线程进入等待状态,直到其他线程调用notify()或notifyAll()或者到了按指定时间。
notify():唤醒在此对象监视器上等待的单个线程。
notifyAll():唤醒在此对象监视器上等待的所有线程。
经典模型:生产者-消费者
//产品类
public class Product {
String name;
int id;
public Product(String name, int id) { this.name = name; this.id = id;}public String toString() { return "Product [name=" + name + ", id=" + id + "]";}
}
//生产者
public class Produter implements Runnable {
ProductBox box;
Thread t;
Produter(ProductBox box) { this.box = box; t = new Thread(this); t.start();}public void run() { for (int i = 1; i < 11; i++) box.put(new Product("产品", i));// 生产 try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }}
}
//消费者
public class Consumer implements Runnable {
ProductBox box;
Thread t;
public Consumer(ProductBox box) { this.box = box; t = new Thread(this); t.start();}@Overridepublic void run() { for (int i = 0; i < 10; i++) { box.get();// 消费 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }}
}
//缓存产品
public class ProductBox {
Product box[] = new Product[5];// 缓存数组
int index = 0;
// 生产产品public synchronized void put(Product p) { if (index == 5) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } box[index++] = p;// 产品存入数组 System.out.println("生产:" + p); notify();}// 消费产品public synchronized Product get() { if (index == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Product p = box[--index];// 从数组取出产品 System.out.println("消费" + p); notify(); return p;}
}
//测试类
public class Test {
public static void main(String[] args) { ProductBox box = new ProductBox(); new Produter(box); new Consumer(box);}
}
0 0
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 线程通信
- 关于委托的一个简单小练习
- 欢迎使用CSDN-markdown编辑器
- 安卓自定义画布 图片,文字相结合成图片 手势放大缩小,文字颜色大小自定义
- 一定要看的。深入理解Objective-C:Category
- jQuery学习之jQuery Ajax用法详解
- 线程通信
- 【NGUI】Rpg对话框
- HDU 2222 Keywords Search
- Python pass 语句
- Unity 内部类的属性序列化问题
- 孤儿进程、僵死进程
- Android轮播循环ViewPager
- 《java入门第一季》二维数组三个案例详解
- JS不间断横向滚动实现代码