{
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+
”is saling ticket”+tickets--); //在这里有可能会打印出负数
}
}
}
}
}
同步函数
除了可以对代码块进行同步外,也可以对函数实现同步,只要在需要同步函数定义前加上synchronized关键字即可。
class ThreadTest implements Runnable
{
private int tickets = 100 ;
public void run()
{
while(true)
{
sale() ;
}
}
public synchronized void sale()
{
if(tickets>0)
{
try
{
Thread.sleep(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();
}
}
程序清单:ThreadDemo6.java
public class ThreadDemo6
{
public static void main(String [] args)
{
ThreadTest t=new ThreadTest();
new Thread(t).start(); //这个线程调用同步代码块
t.str=new String("method");
new Thread(t).start(); //这个线程调用同步函数
}
}
class ThreadTest implements Runnable
{
private int tickets=100;
//同步监视
String str = new String ("");
public void run()
{
if(str.equals("method"))
共21页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21