package?com.umbrella.container.producerConsumer;
import?java.util.LinkedList;
import?java.util.concurrent.TimeUnit;
public?class?ProcuderConsumer<T>?{
????private?final?LinkedList<T>?list?=?new?LinkedList<>();
????private?final?long?MAX?=?10;
????private?int?count?=?0;
????public?synchronized?void?put(T?t)?{
????????while?(list.size()?==?MAX)?{
????????????try?{
????????????????this.wait();
????????????}?catch?(InterruptedException?e)?{
????????????????e.printStackTrace();
????????????}
????????}
????????list.add(t);
????????++count;
????????//不能使用notify,否則可能叫醒的是一個消費者,若此時容器中沒有元素,那么消費者就會一直等一直等。
????????this.notifyAll();
????}
????public?synchronized?T?get()?{
????????T?t?=?null;
????????while?(list.size()?==?0)?{
????????????try?{
????????????????this.wait();
????????????}?catch?(InterruptedException?e)?{
????????????????e.printStackTrace();
????????????}
????????}
????????t?=?list.removeFirst();
????????count--;
????????this.notifyAll();
????????return?t;
????}
????public?static?void?main(String[]?args)?{
????????ProcuderConsumer<String>?pc?=?new?ProcuderConsumer<>();
????????//啟動消費者進程
????????for?(int?i?=?0;?i?<?10;?i++)?{
????????????new?Thread(()?->?{
????????????????for?(int?j?=?0;?j?<?5;?j++)?{
????????????????????System.out.println(pc.get());
????????????????}
????????????},?"consumer?"?+?i).start();
????????}
????????try?{
????????????TimeUnit.SECONDS.sleep(2);
????????}?catch?(InterruptedException?e)?{
????????????e.printStackTrace();
????????}
????????//啟動生產(chǎn)者進程
????????for?(int?i?=?0;?i?<?5;?i++)?{
????????????new?Thread(()?->?{
????????????????for?(int?j?=?0;?j?<?10;?j++)?{
????????????????????pc.put(Thread.currentThread().getName()?+?"?"?+?j);
????????????????????System.out.println("produce?"?+?j);
????????????????}
????????????},?"producer?"?+?i).start();
????????}
????}
}這個代碼哪里寫錯了啊 我記得生產(chǎn)者消費者模式是一直運行下去 不會停的 但我寫的這個很快就結(jié)束了
添加回答
舉報
0/150
提交
取消