public?class?ProducerConsumer<T>?{
????private?final?LinkedList<T>?linkedList?=?new?LinkedList<>();
????private?final?long?MAX?=?10;
????private?int?count?=?0;
????public?synchronized?void?put(T?t)?{
????????while?(linkedList.size()?==?MAX)?{
????????????try?{
????????????????this.wait();
????????????}?catch?(InterruptedException?e)?{
????????????????e.printStackTrace();
????????????}
????????}
????????linkedList.add(t);
????????count++;
????????this.notifyAll();
????}
????public?synchronized?T?get()?{
????????while?(linkedList.size()?==?0)?{
????????????try?{
????????????????this.wait();
????????????}?catch?(InterruptedException?e)?{
????????????????e.printStackTrace();
????????????}
????????}
????????T?t?=?null;
????????t?=?linkedList.removeFirst();
????????count--;
????????this.notifyAll();
????????return?t;
????}
????public?static?void?main(String[]?args)?{
????????ProducerConsumer<String>?pc?=?new?ProducerConsumer<>();
????????for?(int?i?=?0;?i?<?2;?i++)?{
????????????new?Thread(()?->?{
????????????????for?(int?j?=?0;?j?<?6;?j++)?{
????????????????????pc.put(Thread.currentThread().getName()?+?"?");
????????????????????try?{
????????????????????????Thread.sleep(2);
????????????????????}?catch?(InterruptedException?e)?{
????????????????????????e.printStackTrace();
????????????????????}
????????????????}
????????????},?"producer?"?+?i).start();
????????}
????????for?(int?i?=?0;?i?<?10;?i++)?{
????????????new?Thread(()?->?{
????????????????for?(int?j?=?0;?j?<?5;?j++)?{
????????????????????System.out.println(pc.get());
????????????????????try?{
????????????????????????Thread.sleep(2);
????????????????????}?catch?(InterruptedException?e)?{
????????????????????????e.printStackTrace();
????????????????????}
????????????????}
????????????},?"consumer?"?+?i).start();
????????}
????}
}代碼運行就死鎖? 哪里錯了啊
添加回答
舉報
0/150
提交
取消