问题描述
- 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
解决方案
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--);
}
}
解决方案二:
在处理count变量的时候需要同步锁
解决方案三:
刚了解了下synchronized的用法,加上后可以了,原来java线程还有很深入的东西,谢谢各位
时间: 2025-01-20 12:12:01