//模拟生产与消费问题,拿走与取出。我想的结果是线程2,3不断交替输出。但是输出结果是N个线程2后出现3,N个3,后又出现2,交替打印,请问原因在哪?public class sellticket { public static void main(String[] args) {
quantity q=new quantity();
producor pro=new producor(q);
consumer cer=new consumer(q);
new Thread(pro).start();
new Thread(cer).start(); }}
class consumer extends Thread
{quantity q;
consumer(quantity q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
class producor extends Thread
{ quantity q;
producor(quantity q)
{
this.q=q;
}
public void run()
{ while(true){
q.put();
}
}
}
class quantity
{ boolean b=false;
int i;
synchronized void put()
{
if(!b)
try{
wait();
}
catch(Exception e)
{
System.out.print("aaaaa");
}
if(b)
i=1;
System.out.println(Thread.currentThread().getName());
b=true;
notify();
}
synchronized void get()
{
if(b)
try{
wait();
}catch(Exception e)
{
System.out.println(".......");
}
i=0;
System.out.println(Thread.currentThread().getName());
b=false;
notify();
}}
quantity q=new quantity();
producor pro=new producor(q);
consumer cer=new consumer(q);
new Thread(pro).start();
new Thread(cer).start(); }}
class consumer extends Thread
{quantity q;
consumer(quantity q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
class producor extends Thread
{ quantity q;
producor(quantity q)
{
this.q=q;
}
public void run()
{ while(true){
q.put();
}
}
}
class quantity
{ boolean b=false;
int i;
synchronized void put()
{
if(!b)
try{
wait();
}
catch(Exception e)
{
System.out.print("aaaaa");
}
if(b)
i=1;
System.out.println(Thread.currentThread().getName());
b=true;
notify();
}
synchronized void get()
{
if(b)
try{
wait();
}catch(Exception e)
{
System.out.println(".......");
}
i=0;
System.out.println(Thread.currentThread().getName());
b=false;
notify();
}}
quantity q = new quantity();
producor pro = new producor(q);
consumer cer = new consumer(q);
new Thread(pro).start();
new Thread(cer).start(); }}class consumer extends Thread {
quantity q; consumer(quantity q) {
this.q = q;
} public void run() {
while (true) {
q.get();
}
}
}class producor extends Thread {
quantity q; producor(quantity q) {
this.q = q;
} public void run() {
while (true) {
q.put();
}
}
}class quantity {
boolean b = false;
int i; synchronized void put() {
if (b) // 这里不应该是!b
try {
wait();
} catch (Exception e) {
System.out.print("aaaaa");
} if (b)
i = 1;
System.out.println(Thread.currentThread().getName());
b = true;
notify(); } synchronized void get() {
if (!b) // 这里不应该是b
try {
wait();
} catch (Exception e) {
System.out.println(".......");
}
i = 0;
System.out.println(Thread.currentThread().getName());
b = false;
notify();
}}