线程同步

线程同步

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()可以解决这个问题

*/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值