public class MyThread extends Thread
{
static int TOTAL=5;
final static int PRICE=5;
int number;
int money;
public MyThread(int number,int money)
{
this.number=number;
this.money=money;
}
public static void main(String args[])
{
new MyThread(2,20).start();
new MyThread(1,20).start();
new MyThread(2,10).start();
new MyThread(1,10).start();
new MyThread(1,5).start();
}
public synchronized void run()
{
int back=money-PRICE*number;
if(back>TOTAL)
try{
wait();
}
catch(InterruptedException e)
{
throw new RuntimeException(" cannot wait()");
}
System.out.println("Hello! "+Thread.currentThread().getName()+", this is your "+number+" ticket!we give you back"+back+"yuan");
TOTAL=TOTAL+PRICE*number;
notifyAll();
}
}
==========================
请问Thread0和Thread1为什么没有执行呢?也就是前面两个线程没反应,只执行了后面三个线程,而且程序进入了停滞不前的状态??
请问错误在哪里呢?????
{
static int TOTAL=5;
final static int PRICE=5;
int number;
int money;
public MyThread(int number,int money)
{
this.number=number;
this.money=money;
}
public static void main(String args[])
{
new MyThread(2,20).start();
new MyThread(1,20).start();
new MyThread(2,10).start();
new MyThread(1,10).start();
new MyThread(1,5).start();
}
public synchronized void run()
{
int back=money-PRICE*number;
if(back>TOTAL)
try{
wait();
}
catch(InterruptedException e)
{
throw new RuntimeException(" cannot wait()");
}
System.out.println("Hello! "+Thread.currentThread().getName()+", this is your "+number+" ticket!we give you back"+back+"yuan");
TOTAL=TOTAL+PRICE*number;
notifyAll();
}
}
==========================
请问Thread0和Thread1为什么没有执行呢?也就是前面两个线程没反应,只执行了后面三个线程,而且程序进入了停滞不前的状态??
请问错误在哪里呢?????
你要同步就要另外写一个类,然后创建一个对象,让这些线程都共享一个对象,就可以了。