多个线程执行相同的代码,共享票数这个变量,但是我对其中的打印语句有些疑问,先上代码吧:public class test { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnable mt = new MyRunnable();
Thread mt1= new Thread(mt, "一号窗口");
Thread mt2= new Thread(mt, "二号窗口");
Thread mt3= new Thread(mt, "三号窗口");
mt1.start();
mt2.start();
mt3.start();
}
}class MyRunnable implements Runnable{
private int ticket = 10;
public void run(){
for(int i =0;i<500;i++){
if(this.ticket>0){
System.out.println(Thread.currentThread().getName() +"卖票---->"+(this.ticket--));
}
}
}
}
输出结果:一号窗口卖票---->10
一号窗口卖票---->8
一号窗口卖票---->7
一号窗口卖票---->6
一号窗口卖票---->5
一号窗口卖票---->4
一号窗口卖票---->3
一号窗口卖票---->2
一号窗口卖票---->1
二号窗口卖票---->9
从结果上看,第9张票是二号窗口卖出去的,这时候二号窗口的线程应该获得了时间片,但却没有立即打印输出,却在最后打印出来,这是问什么呢?知道的朋友帮帮忙吧,先谢了。ThreadJava
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnable mt = new MyRunnable();
Thread mt1= new Thread(mt, "一号窗口");
Thread mt2= new Thread(mt, "二号窗口");
Thread mt3= new Thread(mt, "三号窗口");
mt1.start();
mt2.start();
mt3.start();
}
}class MyRunnable implements Runnable{
private int ticket = 10;
public void run(){
for(int i =0;i<500;i++){
if(this.ticket>0){
System.out.println(Thread.currentThread().getName() +"卖票---->"+(this.ticket--));
}
}
}
}
输出结果:一号窗口卖票---->10
一号窗口卖票---->8
一号窗口卖票---->7
一号窗口卖票---->6
一号窗口卖票---->5
一号窗口卖票---->4
一号窗口卖票---->3
一号窗口卖票---->2
一号窗口卖票---->1
二号窗口卖票---->9
从结果上看,第9张票是二号窗口卖出去的,这时候二号窗口的线程应该获得了时间片,但却没有立即打印输出,却在最后打印出来,这是问什么呢?知道的朋友帮帮忙吧,先谢了。ThreadJava
class MyRunnable implements Runnable{
private int ticket = 10;
public void run(){
for(int i =0;i<500;i++){
if(this.ticket>0){
synchronized (this) {
System.out.println(Thread.currentThread().getName() +"卖票---->"+(this.ticket--));
}
}
}
}
}
一号窗口卖票---->10
三号窗口卖票---->9
三号窗口卖票---->8
一号窗口卖票---->7
一号窗口卖票---->6
一号窗口卖票---->5
一号窗口卖票---->4
一号窗口卖票---->3
一号窗口卖票---->2
一号窗口卖票---->1
二号窗口卖票---->0
三号窗口卖票---->-1