2 qq 21989117 qq_21989117 于 2015.07.15 17:41 提问

java Thread线程tickets问题

刚学thread,怎么控制台输出会有重复的数目,求大神解答

public class Ticket implements Runnable{
public static int count = 5;
private String name;
public void run(){
for(int i=0;i<=4;i++){
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
if(count >0 ){
System.out.println(Thread.currentThread().getName()+",count= " + this.count--);
}
}
}
public Ticket(){

}
public Ticket(String name){
    this.name = name;
}
public static void main(String[] args){
    Ticket ticket = new Ticket();
    new Thread(ticket,"A").start();
    new Thread(ticket,"B").start();
    new Thread(ticket,"C").start();

}

}

consoles:
B,count= 5
A,count= 5
C,count= 4
B,count= 3
A,count= 2
C,count= 1

3个回答

danielinbiti
danielinbiti   Ds   Rxr 2015.07.15 18:01
已采纳
public static int count = 5;
改成
public static Integer count = 5;

if(count >0 ){
System.out.println(Thread.currentThread().getName()+",count= " + this.count--);
}
改成
synchronized(count){//增加同步锁,当一个线程访问count时,其他不能访问
    if(count >0 ){
      System.out.println(Thread.currentThread().getName()+",count= " + this.count--);
    }
}
bhdgx
bhdgx   2015.07.15 17:47

在处理count变量的时候需要同步锁

qq_21989117
qq_21989117   2015.07.15 21:13

刚了解了下synchronized的用法,加上后可以了,原来java线程还有很深入的东西,谢谢各位

Csdn user default icon
上传中...
上传图片
插入图片