java中关于线程同步的问题

来源:百度知道 编辑:UC知道 时间:2024/05/13 09:44:28
其实很简单 以下是测试的一个程序

public class ThreadTest2 implements Runnable {
int count=1;
public synchronized void acquire() {
while(count==0) {
try {
wait();
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
count--;
}
public synchronized void release() {
while(count==10) {
try {
wait();
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
notifyAll();
count++;
}
public void run() {
Thread temp=Thread.currentThread();
if (temp.getName().substring(0,8).equals("consumer"))
acquire();
if (temp.getName().substring(0,8).equals("producer"))
release();
System.out.println(temp.getName()+" "+count);
}
public static void main(String[] args

你这个生产者消费者不对吧,count怎么说也应该是static的,就是说你只能有一个数据仓库拉,这是一个不共享代码但是共享数据的多线程模式!而且生产者消费者的写法比较严格的,新手最好按照书上的模式写拉

数据仓库
public class Storage {
final int MAX_SIZE;
int count=0;
public Storage(final int max_size) {
super();
MAX_SIZE = max_size;
}
public synchronized void add(String name){
while(count==this.MAX_SIZE){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count++;
System.out.println(name+" has added "+count);
this.notifyAll();

}
public synchronized void del(String name){
while(count==0){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(name+" has deleted "+count);
count--;
th