}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+
”is saling ticket”+tickets--); //在这里有可能会打印出负数
}
}
}
}
}
public class Test
{
public static void main(String aregs[])
{
ThreadTest t = new ThreadTest() ;
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
之所以把String str = new String(“”) ;放在run方法之外,是因为如果将它在run方法中声明,则每个线程都会得到各自的str对象,这样是不可能同步的。
class ThreadTest implements Runnable
{
private int tickets = 100 ;
public void run()
{
//将此变量声明在run方法之中,这样每个线程都拥有各自的str,无法同步
String str = new String(“”);
while(true)
{
synchronized(str) //在这里加上一个同步锁
{
//假如一个线程未执行完,而另一线程又运行此代码,则会出现不同步问题
//为说明问题,将线程延迟
if(tickets>0)
{
try
{
Thread.sleep(10) ; //在这里,让线程休息10毫秒
}
catch(Exception e)
共21页 第1页 第2页 第3页 第4页 第5页 第6页 第7页 第8页 第9页 第10页 第11页 第12页 第13页 第14页 第15页 第16页 第17页 第18页 第19页 第20页 第21页






