package com.thread;
import java.util.LinkedList;
public class MuitlProduceAndTake {
public static void main(String[] args) {
service service = new service();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
@Override
public void run() {
service.produce();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
service.get();
}
}).start();
}
}
}
class service {
private final int MAX_SIZE = 5;
private LinkedList<Object> list = new LinkedList<Object>();
public void produce()
{
synchronized (list)
{
System.out.println("开始生产!");
if (list.size() + 1 > MAX_SIZE) {
System.out.println("已经满了,list不能再放了");
try {
list.wait();
System.out.println("满了,produce正在阻塞");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
list.add("ss");
System.out.println("增加了1,目前大小是:" + list.size());
list.notifyAll();
}
}
public void get()
{
//进入循环后会独占list资源
synchronized (list)
{
System.out.println("开始获取!");
if (list.size() <= 0)
{
System.out.println("库存为0,还不能获取!");
try {
//表示放弃对list资源的独占
list.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
list.remove();
System.out.println("取走了1,目前是"+list.size());
list.notifyAll();
}
}
}
方式二:
package com.thread;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Test {
public static void main(String[] args)
{
services service=new services();
try {
new Thread().wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread().notifyAll();
/*for (int i = 0; i < 15; i++) {
new Thread(new Runnable() {
@Override
public void run() {
service.Produce();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
service.get();
}
}).start();
}*/
}
}
class services{
final int Max_SIZE=5;
BlockingQueue<String> queue=new ArrayBlockingQueue<>(5);
public synchronized void get()
{
if(queue.size()<=0)
{
System.out.println("库存为0还不能获取");
try {
System.out.println("get放弃资源");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
String name=queue.take();
System.out.println("获取数据"+name);
this.notifyAll();
System.out.println("get唤醒线程");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void Produce()
{
if(queue.size()>Max_SIZE)
{
System.out.println("已经满了,不能在生产了!");
try {
System.out.println("produce放弃资源!");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name=new Random().nextInt(1000)+"";
try {
System.out.println("准备生产数据!");
queue.put(name);
System.out.println("已放入数据"+name);
this.notifyAll();
System.out.println("peoduce开始唤醒线程");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}