Java多线程并发笔记03 synchronized减小锁粒度,优化代码执行时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guchunchao/article/details/81697435

 示例代码1:可以对任意Object对象进行加锁

public class ObjectLock {
	public void method1(){
		synchronized (this) {//对象锁
			try {
				System.out.println("method1......");
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void method2(){
		synchronized (ObjectLock.class) {//类锁
			try {
				System.out.println("method2......");
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private Object lock = new Object();
	public void method3(){
		synchronized (lock) {//任何对象锁
			try {
				System.out.println("method3......");
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public static void main(String[] args) {
		final ObjectLock ol = new ObjectLock();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				ol.method1();
			}
		},"t1");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				ol.method2();
			}
		},"t2");
		
		Thread t3 = new Thread(new Runnable() {
			@Override
			public void run() {
				ol.method3();
			}
		},"t3");
		
		
		t1.start();
		t2.start();
		t3.start();
	}
}

示例程序2:String 字符串锁

package com.bjsxt.thread.sync006;

public class StringLock {
	public void method() {
		//如果锁是非new出来的,那么就是一个常量,则被独占while(true)死循环,,若是被new出来的,则2个对象
		/**
		 * 当前线程t2开始
			当前线程t1开始
			当前线程t1结束
			当前线程t2结束
		 */
//		synchronized (new String("字符串常量")) {
			
		/**
		 * 当前线程t1开始
			当前线程t1结束
			当前线程t1开始
			当前线程t1结束
		 */
		synchronized ("字符串常量") {
			try {
				while(true) {
					System.out.println("当前线程"+Thread.currentThread().getName()+"开始");
						Thread.sleep(2000);
					System.out.println("当前线程"+Thread.currentThread().getName()+"结束");
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		final StringLock ol = new StringLock();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				ol.method();
			}
		},"t1");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				ol.method();
			}
		},"t2");
		
		t1.start();
		t2.start();
	}
}

猜你喜欢

转载自blog.csdn.net/guchunchao/article/details/81697435