try
{
Thread.sleep(10) ; //在这里,让线程休息10毫秒
}
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();
}
}
为解决上面的问题,可以引用同步代码块的概念
class ThreadTest implements Runnable
{
private int tickets = 100 ;
//因为此字符串变量声明在类之中,所以所有线程都会共享此对象
String str = new String(“”);
public void run()
{
while(true)
{
synchronized(str) //在这里加上一个同步锁
{
//假如一个线程未执行完,而另一线程又运行此代码,则会出现不同步问题
//为说明问题,将线程延迟
if(tickets>0)
{
try
{
Thread.sleep(10) ; //在这里,让线程休息10毫秒
共21页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21