为什么这行程序加了sychronized 后本来有2个进程的,结果变成了1个进程

来源:百度知道 编辑:UC知道 时间:2024/06/07 10:39:25
class maipiao {

public static void main(String[] args) {
Thread sell = new Thread(new Ticket());

new Thread(sell).start();
new Thread(sell).start();
}
}
class Ticket implements Runnable
{
int ticket = 10;

public synchronized/*这里*/ void run() {
while(true){

if (ticket > 0)
System.out.println(Thread.currentThread().getName() + " " + ticket);
ticket--;
if(ticket<0)
return;
}
}
}

哈哈,又是你,我没认错人吧,你把run方法给同步了,而你new Thread(sell).start();
又使用的同一个对象,当有一个对象在使用 run 方法,另一个就只要等待了

new Thread(new Ticket()).start();
new Thread(new Ticket()).start();

synchronized是线程同步用的,加上它说明一次只能有一个线程可以访问它