java Thread线程tickets问题

代码港湾 论文问答 1

刚学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

回复

共1条回复 我来回复
  • 代码导航
    这个人很懒,什么都没有留下~
    评论
    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--);
        }
    }
    
    0条评论

发表回复

登录后才能评论