线程同步机制(Synchronized)
线程同步 synchronized
多线程操作统一资源(临界资源)时,需要同步机制;
队列和锁
- 不安全买票
public class UnsafeBuyTicket {
	public static void main (String[] args) {
		BuyTicket station =new BuyTicket();
		new Thread(station,"我").start();
		new Thread(station,"你").start();
		new Thread(station,"该死的黄牛").start();
		
	}
}
class BuyTicket implements Runnable{
	private int ticketNums=10;
	boolean flag= true;
	
	@Override
	public void run() {
		// 买票
		while(flag) {
			try {
				buy();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void buy() throws InterruptedException {
		//判断是否有票
		if(ticketNums<=0) {
			flag=false;
			return;
		}
		
		//模拟延时
		Thread.sleep(100);
		//买票
		System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--);
	}
	
}
- 
不安全的取钱(银行) package synchronize; //两个人去银行取钱,账户 public class UnsafeBank { public static void main(String[] args) { Account account=new Account(100,"结婚基金"); Drawing you =new Drawing(account,50,"你"); Drawing girlfriend =new Drawing(account,100,"girlfriend"); you.start(); girlfriend.start(); } } //账户 class Account{ int money;//余额 String name;//卡名 public Account (int money, String name) { this.money=money; this.name=name; } } //银行模拟取款 class Drawing extends Thread{ Account account;//账户 int drawingMoney;//取多少钱 int nowMoney;//手中有多少钱 public Drawing(Account account,int drawingMoney,String name) {//有参构造器 super(name);//给线程名字 this.account=account; this.drawingMoney=drawingMoney; } //取钱方法 public void run() { //先判断有没有钱 if (account.money-drawingMoney<0) { System.out.println(Thread.currentThread().getName()+"钱不够,取不出来!"); return; } try {//增加延时,放大问题发生性 Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //卡内余额=余额-取出的钱; account.money-=drawingMoney; //手里的钱 nowMoney += drawingMoney; System.out.println(account.name+"余额为:"+account.money); System.out.println(this.getName()+"手里的钱为:"+nowMoney); } }
- 
线程不完全的集合 import java.util.List; import java.util.ArrayList; //线程不安全的集合 public class MyTest { public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); for (int i = 0; i < 10000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName() ); }).start(); } Thread.sleep(2000); System.out.println(list.size()); } }
加了锁机制之后,并发线程更安全,但效率更低
synchronized 方法控制对“对象”的访问,每个对象对应一把锁;每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则会阻塞等待;
缺点:效率低;
- 同步方法:public synchronized void method(int args){};
方法前添加锁synchronized:此例syn锁的是BuyTicket对象
public class UnsafeBuyTicket {
	public static void main (String[] args) {
		BuyTicket station =new BuyTicket();
		new Thread(station,"我").start();
		new Thread(station,"你").start();
		new Thread(station,"该死的黄牛").start();
		
	}
}
class BuyTicket implements Runnable{
	private int ticketNums=10;
	boolean flag= true;
	
	@Override
	public void run() {
		// 买票
		while(flag) {
			try {
				buy();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//同步锁在这里**************************
	private synchronized void buy() throws InterruptedException {//添加锁(方法),锁的对象:默认This.(此处是BuyTicket对象)
		//判断是否有票
		if(ticketNums<=0) {
			flag=false;
			return;
		}
		
		//模拟延时
		Thread.sleep(100);
		//买票
		System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--);
	}
	
}
银行取钱加锁:
- 
若在run()方法前添加syn锁: 这里syn锁的对象是Drawing,(银行)。 然而依旧出现负数,因为锁的并不是增删改查的对象(修改的对象);实际上增删改查的对象是账户(Account),所以应该锁Account对象!! //run方法前添加syn锁,锁的对象就是调用该方法的This.对象,Drawing。(即锁的是银行) public synchronized void run() { //先判断有没有钱 if (account.money-drawingMoney<0) { System.out.println(Thread.currentThread().getName()+"钱不够,取不出来!"); return; } try {//增加延时,放大问题发生性 Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //卡内余额=余额-取出的钱; account.money-=drawingMoney; //手里的钱 nowMoney += drawingMoney; System.out.println(account.name+"余额为:"+account.money); System.out.println(this.getName()+"手里的钱为:"+nowMoney); }
- 
若用同步块解决, synchronized(Obj){}Obj -->同步监视器: - 
Obj可以使任何对象(但推荐为临界资源); 
- 
同步方法中无需指定同步监视器,默认就是this,就是这个对象本身,或者是class; 
- 
同步监视器执行过程: 
 1、 第一个线程访问,锁定监视器,进入临界区;
 2、第二个线程访问,发现同步监视器被锁定,无法访问;
 3、第一个线程访问完毕,解锁同步监视器;
 4、第二个线程访问,发现没有锁,然后锁定同步监视器并访问;
 //用代码块锁account对象; public synchronized void run() { //同步块************************* synchronized (account) { //先判断有没有钱 if (account.money-drawingMoney<0) { System.out.println(Thread.currentThread().getName()+"钱不够,取不出来!"); return; } try {//增加延时,放大问题发生性 Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //卡内余额=余额-取出的钱; account.money-=drawingMoney; //手里的钱 nowMoney += drawingMoney; System.out.println(account.name+"余额为:"+account.money); System.out.println(this.getName()+"手里的钱为:"+nowMoney); }//******************** }
- 
安全的集合CopyOnWriteArrayList
JUC 安全类型的集合;
区别于普通的ArrayList,它本身就是安全的集合;

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号