synchronized

线程安全概念:当多个线程访问某一个类(对象或方法)时,这个对象始终都能表现出正确的行为,那么这个类(对象或方法)就是线程安全的。
synchronized:可以在任意对象及方法上加锁,而加锁的这段代码称为"互斥区"或"临界区"

import java.util.concurrent.atomic.AtomicInteger;


public class MyThread extends Thread{
	
	private int count = 5 ;
	
	//synchronized加锁
	public void run(){
		count--;
		System.out.println(this.currentThread().getName() + " count = "+ count);
	}
	
	public static void main(String[] args) {
		/**
		 * 分析:当多个线程访问myThread的run方法时,以排队的方式进行处理
		 * (这里排对是按照CPU分配的先后顺序而定的),
		 * 		一个线程想要执行synchronized修饰的方法里的代码:
		 * 		1 尝试获得锁
		 * 		2 如果拿到锁,执行synchronized代码体内容;
		 * 		  拿不到锁,这个线程就会不断的尝试获得这把锁,直到拿到为止,
		 * 		   而且是多个线程同时去竞争这把锁。(也就是会有锁竞争的问题)
		 */
		MyThread myThread = new MyThread();
		Thread t1 = new Thread(myThread,"t1");
		Thread t2 = new Thread(myThread,"t2");
		Thread t3 = new Thread(myThread,"t3");
		Thread t4 = new Thread(myThread,"t4");
		Thread t5 = new Thread(myThread,"t5");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
	}
}

run方法加synchronized和不加synchronized,执行结果不同。

加synchronized

t1 count = 4
t5 count = 3
t4 count = 2
t2 count = 1
t3 count = 0

不加synchronized(结果不唯一)

t2 count = 3
t3 count = 2
t1 count = 3
t4 count = 1
t5 count = 0

多个线程多个锁:多个线程,每个线程都可以拿到自己指定的锁,分别获得锁之后,执行synchronized方法体内容

关键字synchronized取得的锁都是对象锁,而不是把一段代码(方法)当做锁, 所以代码中哪个线程先执行synchronized关键字的方法,哪个线程就持有该方法所属对象的锁(Lock), 在静态方法上加synchronized关键字,表示锁定.class类,类一级别的锁(独占.class类)。

public class MultiThread {

	private int num = 0;
	
	/** static */
	public synchronized void printNum(String tag){
		try {
			
			if(tag.equals("a")){
				num = 100;
				System.out.println("tag a, set num over!");
				Thread.sleep(1000);
			} else {
				num = 200;
				System.out.println("tag b, set num over!");
			}
			
			System.out.println("tag " + tag + ", num = " + num);
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	//注意观察run方法输出顺序
	public static void main(String[] args) {
		
		//俩个不同的对象,线程获得的就是两个不同的锁,互不影响。
		final MultiThread m1 = new MultiThread();
		final MultiThread m2 = new MultiThread();
		
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				m1.printNum("a");
			}
		});
		
		Thread t2 = new Thread(new Runnable() {
			@Override 
			public void run() {
				m2.printNum("b");
			}
		});		
		
		t1.start();
		t2.start();
		
	}
	
	
	
	
}

执行结果:

不加static(结果不唯一)

tag b, set num over!
tag a, set num over!
tag b, num = 200
tag a, num = 100

加static

tag b, set num over!
tag b, num = 200
tag a, set num over!
tag a, num = 100

或者

tag a, set num over!
tag a, num = 100
tag b, set num over!
tag b, num = 200

对象锁的同步和异步问题

同步的概念就是共享,如果不是共享的资源,就没有必要同步 

异步的概念就是独立,互相之间不受到任何制约。就像在页面发起Ajax请求,还可以继续浏览或操作页面的内容 

同步的目的就是为了线程安全,满足两个特性:原子性/可见性

public class MyObject {

	public synchronized void method1(){
		try {
			System.out.println(Thread.currentThread().getName());
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/** synchronized */
	public void method2(){
			System.out.println(Thread.currentThread().getName());
	}
	
	public static void main(String[] args) {
		
		final MyObject mo = new MyObject();
		
		/**
		 * 分析:
		 * t1线程先持有object对象的Lock锁,t2线程可以以异步的方式调用对象中的非synchronized修饰的方法
		 * t1线程先持有object对象的Lock锁,t2线程如果在这个时候调用对象中的同步(synchronized)方法则需等待,也就是同步
		 */
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				mo.method1();
			}
		},"t1");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				mo.method2();
			}
		},"t2");
		
		t1.start();
		t2.start();
		
	}
	
}

执行结果:

method2不加synchronized:几乎同时输出

method2加synchronized:t1输出一段时间后输出t2

脏读
业务整体需要使用完整的synchronized,保持业务的原子性。对于对象的同步和异步方法,在设计程序的时候,一定要考虑问题的整体,不然就会出现数据不一致的错误

public class DirtyRead {

	private String username = "zhang";
	private String password = "123";

    /**
     *在对一个对象的方法加锁时,需要考虑业务的整体性,即为setValue / getValue
     * 同时加锁synchronized关键字,保证业务(service)的原子性,不然会出现业务错误
     * (也从侧面保证业务的一致性)。
     */
	public synchronized void setValue(String username, String password){
		this.username = username;
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		this.password = password;
		
		System.out.println("setValue最终结果:username = " + username + " , password = " + password);
	}
	
	public void getValue(){
		System.out.println("getValue方法得到:username = " + this.username + " , password = " + this.password);
	}
	
	
	public static void main(String[] args) throws Exception{
		
		final DirtyRead dr = new DirtyRead();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				dr.setValue("z3", "456");		
			}
		});
		t1.start();
		Thread.sleep(1000);
		
		dr.getValue();
	}
	
	
	
}

执行结果:

get不加synchronized

getValue方法得到:username = z3 , password = 123
setValue最终结果:username = z3 , password = 456

get加synchronized

setValue最终结果:username = z3 , password = 456
getValue方法得到:username = z3 , password = 456

synchronized的重入问题

/**
 * 三个方法都有synchronized修饰,其中method1调用method2,method2调用method3。
 */
public class SyncDubbo1 {

	public synchronized void method1(){
		System.out.println("method1..");
		method2();
	}
	public synchronized void method2(){
		System.out.println("method2..");
		method3();
	}
	public synchronized void method3(){
		System.out.println("method3..");
	}
	
	public static void main(String[] args) {
		final SyncDubbo1 sd = new SyncDubbo1();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				sd.method1();
			}
		});
		t1.start();
	}
}

执行结果:

method1..
method2..
method3.. 

/**
 * 关键字synchronized拥有锁重入的功能,也就是在使用synchronized时,当一个线程得到了对象的锁后,
 * 再次请求此对象是可以再次得到该对象的锁
 *
 */
public class SyncDubbo2 {

	static class Main {
		public int i = 10;
		public synchronized void operationSup(){
			try {
				i--;
				System.out.println("Main print i = " + i);
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

    /**
     * 继承了父类的方法以及成员变量
     * 如果有父子继承关系的时候,方法都加synchronized修饰,调用也是线程安全
     */

	static class Sub extends Main {
		public synchronized void operationSub(){
			try {
				while(i > 0) {
					i--;
					System.out.println("Sub print i = " + i);
					Thread.sleep(100);		
					this.operationSup();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				Sub sub = new Sub();
				sub.operationSub();
			}
		});
		
		t1.start();
	}
	
	
}

执行结果:

Sub print i = 9
Main print i = 8
Sub print i = 7
Main print i = 6
Sub print i = 5
Main print i = 4
Sub print i = 3
Main print i = 2
Sub print i = 1
Main print i = 0

synchronized异常

对于web应用程序,异常释放锁的情况,如果不及时处理,很可能对应用程序业务逻辑产生严重的错误。比如执行一个队列任务,很多对象都在等待第一个对象正确执行完毕再去释放锁,但是第一个对象由于异常的出现,导致业务逻辑没有正确执行完毕,就释放了锁,那么后面的对象执行的都是错误的逻辑。所以在编写代码的时候,一定要注意

public class SyncException {

	private int i = 0;
	public synchronized void operation(){
		while(true){
			try {
				i++;
				Thread.sleep(100);
				System.out.println(Thread.currentThread().getName() + " , i = " + i);
				if(i == 10){
					Integer.parseInt("a");
//					throw new RuntimeException();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
                System.out.println("log.info i = "+i);
//                throw new RuntimeException();
//                continue;
                /**
                 * 1.有问题的数据记录日志(对后续无影响)
                 * 2.抛异常(整体操作)
                 */
			}
		}
	}
	
	public static void main(String[] args) {
		
		final SyncException se = new SyncException();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				se.operation();
			}
		},"t1");
		t1.start();
	}
	
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值