62,621
社区成员
发帖
与我相关
我的任务
分享
public class MyWait {
public static void main(String[] args) {
Containers cs = new Containers();
Consumer con = new Consumer(cs);
Producer p = new Producer(cs);
Thread c1 = new Thread(con);
Thread c2 = new Thread(p);
c2.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
c1.start();
}
}
class Containers{
int count = 1;
int index = 1;
public synchronized void put() {
System.out.println("put..."+(++index));
if(index == 2) {
try {
System.out.println("p.");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("put-wait."+count++);
notify();
System.out.println("notify-put!"+count++);
}
public synchronized void get() {
System.out.println("get..."+(--index));
if(index == 1) {
try {
System.out.println("g.");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("get-wait."+count++);
notify();
System.out.println("get-afer-notify!"+count++);
}
}
class Consumer implements Runnable{
Containers cs;
Consumer(Containers cs) {
this.cs = cs;
}
public void run() {
while(true) {
cs.get();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable{
Containers cs;
Producer(Containers cs) {
this.cs = cs;
}
public void run() {
while(true) {
cs.put();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Containers {
int count = 1;
int index = 0;
public synchronized void put() {
System.out.println("put..." + (++index));
if (index == 2) {
try {
System.out.println("p.");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("put-wait." + count++);
this.notify();
System.out.println("notify-put!" + count++);
}
public synchronized void get() {
System.out.println("get..." + (--index));
if (index == 0) {
try {
System.out.println("g.");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("get-wait." + count++);
this.notify();
System.out.println("get-afer-notify!" + count++);
}
}