JAVA多线程安全问题
class Tickets implements Runnable
{
private int num=100;
public void run()
{
show();
}
public void show()
{
while(num>0)
{
try{
Thread.sleep(10);
}
catch(InterruptedException e)
{}
num--;
System.out.println("This is"+Thread.currentThread().getName()+"window,there are "+num+"tickets");
}
}
}
public class Safety_Problem_Of_Thread {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Tickets T=new Tickets();// TODO code application logic here
Thread t1=new Thread(T);
Thread t2=new Thread(T);
t1.start();
t2.start();
}
}
——————————————————————————————————
结果:
This isThread-1window,there are 99tickets
This isThread-0window,there are 99tickets
This isThread-0window,there are 98tickets
This isThread-1window,there are 98tickets
This isThread-1window,there are 96tickets
This isThread-0window,there are 96tickets
This isThread-0window,there are 95tickets
This isThread-1window,there are 95tickets
This isThread-1window,there are 94tickets
This isThread-0window,there are 94tickets
This isThread-1window,there are 93tickets
This isThread-0window,there are 92tickets
结果只列出了一部分。我知道这段代码存在安全问题,并没有设置同步。但是为什么结果中会输出两个99,98,96,95........这是什么原因呢,可否分析一下???谢谢