线程同步
class ThreadDemo1
{
public static void main(String[] args){
/* new TestThread().start();
while(true){
System.out.println("main() "+Thread.currentThread().getName());
}*/
/* new TestThread().start();
new TestThread().start();
new TestThread().start();
new TestThread().start();
*/
/*这里产生了四个线程对象,每个线程对象都有100张票,并且各自售自己的100张票,为了使四个窗
售的是同样的100张票,就只能产生一个线程对象。如下*/
/*
TestThread tt=new TestThread();
tt.start();
tt.start();
tt.start();
tt.start();*/
/*这种方法只产生一个线程对象,因为只有一个线程,所以只有一个窗口在售票,为了使四个窗口售同样的100
张票我们就只能产生一个资源对象而又必须创建多个线程去处理这个对象,我们实现Runnable接口*/
TestThread tt=new TestThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TestThread implements Runnable//extends Thread
{
int tickets=100;
String str=new String("");/*这句不可以放到run方法里面,如果放在run方法里面,四个线程将会产生四个str,不能起到线程同步的作用*/
public void run()
{
while(true)
{
synchronized(str)
{
if(tickets>0)
{
try{Thread.sleep(80);}catch(Exception e){System.out.println("系统故障!请重试!");}
System.out.println(Thread.currentThread().getName()+" is saling ticket "+tickets--);
}
else System.exit(0);
}
}
}
}
/*添加Thread.sleep(80);语句后出现多个线程售出同一张票的错误,这是由于判断tickets>0语句执行后没有
立即执行打印语句System.out.println(Thread.currentThread().getName()+" is saling ticket "+tickets--);
导致号码打印错误,用synchronized()可以解决这个问题
*/