多线程同步代码块的两种方法

代码块同步

public void print2(){
		
		synchronized (this) {
			System.out.print("w");
			System.out.print("o");
			System.out.print("r");
			System.out.print("l");
			System.out.print("d");
			System.out.println();
		}
		
	}
方法同步
	public   synchronized  void print1(){
		//方法同步代码块
		
		//1 synchronized(所对象){需要完整执行代码;}
		//所对象 : 任何对象都可以,注意,多个线程只有公用同一个锁对象才可以保证同步
		// 2 . 使用同步方法实现相同效果
		//000普通的同步方法,锁对象是this
		// 静态方法对象不是this  是字节码对象   类名.class
		
		//同步方法  同步代码块 
		
		//synchronized(obj) {
			System.out.print("h");
			System.out.print("e");
			System.out.print("l");
			System.out.print("l");
			System.out.print("o");
			System.out.println();	
		//}
		
	}


猜你喜欢

转载自blog.csdn.net/qq_38763885/article/details/80867268