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

 

 示例代码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();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值