首页 > 代码库 > 深入同步语法

深入同步语法

1.深入synchronized关键字

class Service{
	public void fun1(){
		synchronized(this){
			try{
				Thread.sleep(3 * 1000);
			}catch(Exception e){
				System.out.println(e);
			}
			System.outprintln(fun1);
		}
	}
	public void fun2(){
		synchronized(this){
			System.out.println(fun2);
		}
	}
}

class MyThread1 implements Runnable{
	private Service service;
	
	public MyThread1(Service service){
		this.service = service;
	}
	
	public void run{
		service.fun1();
	}
}

class MyThread2 implements Runnable{
	private Service service;
	
	public MyThread2(Service service){
		this.service = service;
	}
	
	public void run{
		service.fun2();
	}
}

class Test{
	public static void main(String args[]){
		Service service = new Service();
		Thread1 t1 = new Thread1(new MyThread1(service));
		Thread2 t2 = new Thread2(new MyThread2(service));
	}
}


2.同步方法

class Service{
	//同步方法只需要把synchronized放在返回值(void)的前面即可
	public synchronized void fun1(){
		try{
				Thread.sleep(3 * 1000);
		}catch(Exception e){
				System.out.println(e);
		}
		System.outprintln(fun1);
		
	}
	public synchronized void fun2(){
			System.out.println(fun2);
	}
}
同步方法跟同步代码快的功能类似,只不过同步代码快可以指定究竟锁住哪一个对象,而同步方法锁住的就是this

深入同步语法