问题描述
- java synchronized问题 求指导
-
import java.util.LinkedList;
public class Test3 {
LinkedList storage= new LinkedList();
int max=10;
public Test3()
{
}
public void start(){
new product().start();
new c().start();
}
class product extends Thread{
public void run(){
while(true){
synchronized (storage) {
while(storage.size()==max){
System.out.println("仓库满了,你不要生产了");
try {
storage.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}} Object o=new Object(); if(storage.add(o)){ System.out.println("继续生产,往仓库里放"); try { Thread.sleep(1000); storage.notify(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } class c extends Thread{ public void run(){ while(true){ synchronized (storage) { while(storage.size()==0){ System.out.println("仓库空了"); try { storage.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } storage.removeLast(); System.out.println("正在取出"); try { Thread.sleep(2000); storage.notify(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } public static void main(String[] args) { Test3 t=new Test3(); t.start(); }
}
时间: 2024-10-01 23:57:20