class comparedemo1
{
public static void main(String[] args)
{
ticket t = new ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(10);}catch(InterruptedException e){}
t.flag = false;
t2.start();
}
}
class ticket implements Runnable
{
private int num = 100;
Object obj = new Object();
boolean flag = true;
public void run(){
if (flag)
{
while(num>0){
synchronized(obj){
if(num > 0){
try{Thread.sleep(10);}catch(InterruptedException e ){}
System.out.println(Thread.currentThread().getName()+"...obj..."+num--);
}
}
}
}
else{
while(num>0){
show();
}
}
}
public synchronized void show(){
if(num > 0){
try{Thread.sleep(10);} catch(InterruptedException e ){}
System.out.println(Thread.currentThread().getName()+"...function..."+num--);
}
}
}
为什么主线程被睡之前之后打印的结果不同,请问各位大佬,是什么原因导致的线程打印结果的改变?
被睡之前:
被睡之后: