/*
*目的:测试同步代码块和同步函数锁定同一个对象才能实现线程安全
*其实我们能够实现线程同步其实就是因为我们在运行到某一个线程的时候,设置了一个标志
*也就是我们锁定了一个对象,要实现线程的同步,我们每次锁定的对象必须要是同一个
*/
class Lesson5TestDemo1
{
public static void main(String [] args)
{
Lesson5TestDemo2 rr = new Lesson5TestDemo2();
//调用start函数只是让这个线程处于就绪状态,并不是已经马上就去运行这个线程,可能还运行在其他的线程上,只不过让这个线程处于就绪状态了
new Thread(rr).start();
//这是让其他的线程停下,让这个就绪状态的线程运行起来
try{Thread.sleep(1);}catch(Exception e){}
rr.str = new String("method");
new Thread(rr).start();
//new Thread(rr).start();
//new Thread(rr).start();
}
}
class Lesson5TestDemo2 implements Runnable
{
private int tickets = 100;
String str = new String("");
public void run()
{
if(str.equals(""))
{
//这里锁定的str,由于同步代码块和同步函数锁定不是同一个对象,所以还是会出错
//要是我们的同步代码块和我们的同步函数锁定 同一个对象,那么就不会出错了
//synchronized(str)
synchronized(this)
{
while(true)
{
if(tickets > 0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println("nosale");
System.out.println(Thread.currentThread().getName() + " is saling ticket of " + tickets--);
}
}
}
}
else
{
//其实这里锁定的是this
sale();
}
}
public synchronized void sale()
{
while(true)
{
if(tickets > 0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println("sale");
System.out.println(Thread.currentThread().getName() + " is saling ticket of " + tickets--);
}
}
}
}