剛學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
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--);
}
}