新手求助线程小问题,感谢大侠不吝赐教
小弟最近在自学java,在线程处遇到一卖票程序,有几处百思不得其解,望各位大侠不吝赐教,小弟谢过class A implements Runnable
{
public int tickets = 100;
String str = new String("ironman");
public void run()
{
while(true)
{
synchronized(str)
{
if(tickets>0)
{
System.out.printf("%s线程正在卖出第%d张票\n",Thread.currentThread().getName(),tickets);
tickets--;
}
else
{
break;
}
}
}
}
}
class TestTickets_2
{
public static void main(String[] args)
{
A aa = new A();
Thread str1 = new Thread(aa);
str1.start();
Thread str2 = new Thread(aa);
str2.start();
}
}
问题1:为何只会有一个线程卖票,无法实现交替卖票?
问题2:若将主线程改为
class TestTickets_2
{
public static void main(String[] args)
{
Thread str1 = new Thread(new A());
str1.start();
Thread str2 = new Thread(new A());
str2.start();
}
}
为何会出现每张票被重复卖出的现象?