java.lang.Object -public void notify()//唤醒这个对象监视器正在等待获取锁的一个线程 -public void notifyAll()//唤醒这个对象监视器上正在等待获取锁的所有线程 -public void wait()//导致当前线程等待另一个线程调用notify()或notifyAll() -public void wait(long timeout)// 导致当前线程等待另一个线程调用notify()或notifyAll(),或者达到timeout时间 -public void wait(long timeout, int nanos)//与上个方法相同,只是将时间控制到了纳秒nanos
package com.producerconsumer;
import java.util.Queue;
/**
* 生产者
* Created by yulinfeng on 2017/5/11.
*/
public class Producer implements Runnable{
private final Queue<String> queue;
private final int maxSize;
public Producer(Queue<String> queue, int maxSize) {
this.queue = queue;
this.maxSize = maxSize;
}
public void run() {
produce();
}
/**
* 生产
*/
private void produce() {
try {
while (true) {
synchronized (queue) {
if (queue.size() == maxSize) {
System.out.println("生产者:仓库满了,等待消费者消费");
queue.wait();
}
System.out.println("生产者:" + queue.add("product"));
queue.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.producerconsumer;
import java.util.Queue;
/**
* 消费者
* Created by yulinfeng on 2017/5/11.
*/
public class Consumer implements Runnable {
private final Queue<String> queue;
public Consumer(Queue<String> queue) {
this.queue = queue;
}
public void run() {
consume();
}
/**
* 消费
*/
private void consume() {
synchronized (queue) {
try {
while (true) {
if (queue.isEmpty()) {
System.out.println("消费者:仓库空了,等待生产者生产");
queue.wait();
}
System.out.println("消费者:" + queue.remove());
queue.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.producerconsumer;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by yulinfeng on 2017/5/11.
*/
public class Main {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<String>();
int maxSize = 100;
Thread producer = new Thread(new Producer(queue, maxSize));
Thread consumer = new Thread(new Consumer(queue));
producer.start();
consumer.start();
}
}
java.lang.Thread -public void join() -public void sleep() -public static void yield() -……
package com.join;
public class Main {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(new Task(0));
Thread t2 = new Thread(new Task(0));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.print("main结束");
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有