package n;
public class box {
int x;
boolean i=false;
public synchronized void getX() {//加锁
if(i) {
System.out.println("拿了第"+x+"瓶");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i=!i;
//唤醒其他线程
notifyAll();
}
public synchronized void setX(int x) {//加锁
System.out.println("生产第"+x+"瓶");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//唤醒其他线程
i=true;
notifyAll();
}
}
package n;
public class box {
int x;
boolean i=false;
public synchronized void getX() {//加锁
if(i) {
System.out.println("拿了第"+x+"瓶");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i=!i;
//唤醒其他线程
notifyAll();
}
public synchronized void setX(int x) {//加锁
System.out.println("生产第"+x+"瓶");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//唤醒其他线程
i=true;
notifyAll();
}
}
线程的开启用start(),然后他会自动去执行run的