同步函数以this为锁

/*
	同步函数用的是this锁
	
	函数需要被对象调用。那么函数都有一个所属对象调用,就是this
	所以同步函数使用的锁是this

	
	通过该程序进行验证

	使用两个线程来卖票

	一个线程在同步代码块中
	一个线程在同步函数中
	都在执行卖票操作


*/

class Ticket implements	Runnable
{
	private int tick = 1000;
	
	//Object obj = new Object();

	boolean flag = true;

	public void run()
	{
		if(flag)//第一个进入的线程实行下面代码
		{
				while(true)
				{
					//synchronized(obj)//由于同步函数的是以this对象为锁的 此处如果使用obj对象作为锁
										//则不能实现同步 输出的数据会出现错误 程序的安全性不能得到保证
					synchronized(this)//和下面的show函数使用同样的锁 可以保证同步
					{
						if(tick>0)
						{
							try{Thread.sleep(40);}catch(Exception e){}
							System.out.println(Thread.currentThread().getName() +" .....code..."+ tick--);

						}
					}
				}
		}//第二个进入的代码实行下面代码
		else
			while(true)
				show();//this.show();
	
	}
	public synchronized void show()//同步函数 以this为锁
	{
		if(tick>0)
		{
			try{Thread.sleep(40);}catch(Exception e){}
			System.out.println(Thread.currentThread().getName() +" .....show..."+ tick--);
		}		
	}

}


class ThisLockDemo
{
	public static void main(String []args)
	{
		Ticket t = new Ticket();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
	
		t1.start();//开启第一个线程  但不一定马上执行
		
		t.flag = false;//改变标志
		try{Thread.sleep(40);}catch(Exception e){}//让主线程睡眠40毫秒  保证第一个线程先开始运行 且标志位改变

		t2.start();	
	}
}

原文地址:https://www.cnblogs.com/dengshiwei/p/4258522.html