138_多线程(多线程-同步函数的锁是this)

/*
同步函数用的是哪一个锁呢?
函数需要被对象调用。那么函数都有一个所属对象的引用,就是this
所以同步函数使用的锁是this
*/
class TWindow implements Runnable{
	private int ticketNum =100;
	//Object obj = new Object();
	public void run(){
		while(true){
			this.show();
		}
	}
	public sychronized void show(){
		if(ticketNum > 0){
			try{
					Thread.sleep(10);
			}
			catch(Exception e){
						
			}
			System.out.println(Thread.currentThread().getName()
			+" sale "+ ticketNum--);
		}
	}
}

class ThreadDemo{
	public static void main(String[] args){
		TWindow t = new TWindow();
		
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		Thread t3 = new Thread(t);
		Thread t4 = new Thread(t);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

/*
通过该程序进行验证:
使用两个线程买票
一个线程在同步代码块中
一个在同步函数中,都在执行买票动作
*/

class TWindow implements Runnable{
	private int ticketNum =100;
	Object obj = new Object();
	boolean flag = true;
	public void run(){
		if(flag){
			while(true){
				sychronized(obj){
					if(ticketNum > 0){
						try{
							Thread.sleep(10);
						}
						catch(Exception e){
									
						}
						System.out.println(Thread.currentThread().getName()
						+" code "+ ticketNum--);
					}					
				}
			}
		}
		else
			while(true)
				show();
	}
	public sychronized void show(){
		if(ticketNum > 0){
			try{
					Thread.sleep(10);
			}
			catch(Exception e){
						
			}
			System.out.println(Thread.currentThread().getName()
			+" sale "+ ticketNum--);
		}
	}
}

class ThreadDemo{
	public static void main(String[] args){
		TWindow t = new TWindow();
		
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		
		t1.start();
		t.flag = false;
		t2.start();
		
	}
}



_________________

如果同步函数被静态static修饰,使用的锁是什么呢?
通过验证,发现不是this,因为静态方法中也不可以定义this。
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码
文件对象:类名.class。该对象的类型是class。

静态的同步方法,使用的锁是该方法所在类的字节码文件对象。也就是
类名.class。

猜你喜欢

转载自317324406.iteye.com/blog/2249364