Java-----线程的同步与锁定

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

同步:并发 多个线程访问同一份资源 确保资源安全 ----->线程安全
Hashtable -----put方法
StringBuffer-----appent方法

synchronized----同步 相当于拿到了一把锁,把资源锁住
一.同步块
synchronized(引用类型|this|类.class){
}
二.同步方法

package com.kennosaur.syn;


public class Syn01 {

	public static void main(String[] args) {
		//真实角色
		Web12306 web = new Web12306();
		//代理
		Thread t1 = new Thread(web, "路人甲");
		Thread t2 = new Thread(web, "路人乙");
		Thread t3 = new Thread(web, "攻城狮");
		//启动线程
		t1.start();
		t2.start();
		t3.start();
	}

}

class Web12306 implements Runnable{
	private int num=10;
	private boolean flag = true;
	@Override
	public void run() {
		while (flag) {
			test6();
		}
	}
	
	//线程不安全,锁定资源不正确
	public void test6() {			
		if (num<=0) {
			flag = false; 
			return ;
		}
		synchronized(this) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
		}
	}
	//线程不安全,锁定资源不正确
	public void test5() {
		synchronized((Integer)num) {
			if (num<=0) {
				flag = false; 
				return ;
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
		}
	}
	//锁定范围不正确,线程不安全
	public void test4() {
		synchronized(this) {
			if (num<=0) {
				flag = false; 
				return ;
			}
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"抢到了"+num--);		
	}
	//同步块     线程安全,锁定正确
	public void test3() {
		synchronized(this) {
			if (num<=0) {
				flag = false; 
				return ;
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
		}
	}
	//同步方法  线程安全,锁定正确
	public synchronized void test2() {
		if (num<=0) {
			flag = false; 
			return;
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
	
	}
	
	//线程不安全
	public void test1() {
		if (num<=0) {
			flag = false; 
			return ;
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
	}
}

三.synchronized(类.class){

}

猜你喜欢

转载自blog.csdn.net/Miracle_Gaaral/article/details/89071694