多线程(续2)

  1. 线程同步(队列+锁)会损失性能是肯定的
  • 并发:同一个对象被多个线程所控制。同一个时间片
  • 并行:同一时刻
处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象。这个时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个*对象的等待池*形成队列,等待前面线程使用完毕,下一个线程再使用。
  • 由于同一个进程的线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在被访问时的正确性,在访问时加入***锁机制 synchornized,当一个线程获得对象的排他锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
    • 一个线程持有锁会导致其他使用该锁的线程挂起
    • 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
    • 如果一个优先级高的线程等待一个优先级低的线程,会导致优先级倒置,引发各种性能问题
    • 鱼和熊掌不可兼得,安全和性能不可兼得
  1. 同步方法
    在这里插入图片描述
  2. 同步方法
  • java里面是利用get、set方法来对java对象进行保护机制。在进程里面,我们只需要针对方法提出一套机制,这套机制就是synchronized
    • synchronized方法

    • synchronized块(synchronized(obj){})obj通常为需要修改的对象,比如:银行里的账户

      1. obj称为同步监视器;他可以是任何对象,但是推荐使用共享资源作为同步监视器;同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class(反射中讲)
      2. 同步监视器的执行过程
      • 第一个线程访问,锁定同步监视器,执行其中代码
      • 第二个线程访问,发现同步监视器被锁定,无法访问
      • 第一个线程访问完毕,解锁同步监视器
      • 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
        同步方法:public synchronized void method(int args){}
synchronized方法控制对“对象”的访问,每个对相对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则会造成线程堵塞,方法一旦执行,就独占该锁,直到该方法返回时才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
缺陷:若将一个大的方法申明为synchronized将会影响效率

案例:1.买票2.list3.银行4.JUC

public class BuyTicket {
	public static void main(String[] args) {
		Buyer buyer = new Buyer();
		new Thread(buyer,"a").start();
		new Thread(buyer,"b").start();
		new Thread(buyer,"c").start();
	}
}
//买票
class Buyer implements Runnable {
	private int tnum=10;
	private boolean flag=true;
	@Override
	public void run() {
		while(flag) {
			buy();
		}
	}
	public synchronized void buy() {
		if(tnum<=0) {
			flag=false;
			return;
		}
		System.out.println(Thread.currentThread().getName()+"买到了"+tnum);
		tnum--;
	}
}
public class ConnNosafe {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 1000000; i++) {
			new Thread(()->{
				synchronized (list) {
					list.add(Thread.currentThread().getName());
				}
			}).start();
		}
		System.out.println(list.size());
	}
}
public class GiveMoney {
	public static void main(String[] args) {
		Ancount a = new Ancount("结婚", 1000);
		Bank c = new Bank(a, 950, "cc");
		Bank b = new Bank(a, 100, "bb");
		c.start();
		b.start();
	}
}
//账户
class Ancount {
	String name;
	int mString;
	public Ancount(String name, int mString) {
		super();
		this.name = name;
		this.mString = mString;
	}
}
//银行
class Bank extends Thread {
	private Ancount a;
	private int getMoney;
	private int handMoney;
	public Bank(Ancount a, int getMoney, String name) {
		super(name);
		this.a = a;
		this.getMoney = getMoney;
	}
	@Override
	public void run() {
		synchronized (a) {
			if(getMoney >= a.mString) {
				System.out.println(Thread.currentThread().getName()+"-->"+a.name + "账户余额不足");
				return;
			}
			handMoney += getMoney;
			a.mString -= getMoney; 
			System.out.println(a.name +"余额为" + a.mString);
			System.out.println(Thread.currentThread().getName() +"手里的钱有" + handMoney);
		}
	}
}
public class TestJUCList {
	public static void main(String[] args) {
		CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
		for (int i = 0; i < 10000; i++) {
			new Thread(()->{
				list.add(Thread.currentThread().getName());
			}).start();
		}
		System.out.println(list.size());
		
	}
}
  1. 死锁
  • 两个资源共同抢夺一个资源,然后谁都不放手,最后资源崩溃,这就叫死锁。官方:某一个同步块同时拥有“两个以上对象的锁”。(多个线程相互抱着对方所需要的资源,然后形成僵持。)
    案例:化妆
public class TestDeadLock {
	public static void main(String[] args) {
		makeUp g1 = new makeUp(1, "sb");
		makeUp g2 = new makeUp(0, "zz");
		g1.start();
		g2.start();
	}
}
//镜子
class mirror {
	
}
//口红
class mouthRed {
	
}
//化妆
class makeUp extends Thread {
	static mirror m=new mirror();
	static mouthRed mRed=new mouthRed();
	private int choice;
	private String girlString;
	public makeUp(int choice, String girlString) {
		super();
		this.choice = choice;
		this.girlString = girlString;
	}
	@Override
	public void run() {
		try {
			make();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void make() throws InterruptedException {
		if(choice == 0) {
			synchronized (m) {
				System.out.println(this.girlString + "获得了镜子的锁");
				Thread.sleep(1000);
				synchronized (mRed) {
					System.out.println(this.girlString + "获得了口红的锁");
				}
			}
		}else {
			synchronized (mRed) {
				System.out.println(this.girlString + "获得了口红的锁");
				Thread.sleep(2000);
				synchronized (m) {
					System.out.println(this.girlString + "获得了镜子的锁");
				}
			}
		}
	}
}
上面是死锁,解决方法是把那个syn块拿出来就行,别让他们同时调用对方的锁
public class TestDeadLock {
	public static void main(String[] args) {
		makeUp g1 = new makeUp(1, "sb");
		makeUp g2 = new makeUp(0, "zz");
		g1.start();
		g2.start();
	}
}
//镜子
class mirror {
	
}
//口红
class mouthRed {
	
}
//化妆
class makeUp extends Thread {
	static mirror m=new mirror();
	static mouthRed mRed=new mouthRed();
	private int choice;
	private String girlString;
	public makeUp(int choice, String girlString) {
		super();
		this.choice = choice;
		this.girlString = girlString;
	}
	@Override
	public void run() {
		try {
			make();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void make() throws InterruptedException {
		if(choice == 0) {
			synchronized (m) {
				System.out.println(this.girlString + "获得了镜子的锁");
				Thread.sleep(1000);
			}
			synchronized (mRed) {
				System.out.println(this.girlString + "获得了口红的锁");
			}
		}else {
			synchronized (mRed) {
				System.out.println(this.girlString + "获得了口红的锁");
				Thread.sleep(2000);
			}
			synchronized (m) {
				System.out.println(this.girlString + "获得了镜子的锁");
			}
		}
	}
}
  • 产生死锁的四个必要条件
  1. 互斥条件:一个资源每次只能被一个进程使用
  2. 请求与保持条件:一个进程因请求资源而堵塞时,对已获得的资源保持不放
  3. 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
  4. 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
    要想破坏死锁,只要想办法破坏其中的任意一个或者多个条件就可以避免死锁发生
  5. Lock锁
  • 从jdk5.0开始,java提供了更强大的线程同步机制—通过显式定义同步锁对象来实现同步。同步锁使用lock对象充当。
  • java.util.concurrent.lock.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
  • ReentrantLock类实现了Lock,它拥有与synchroized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁、释放锁。
public class TestLockLock {
	public static void main(String[] args) {
		Buy buy = new Buy();
		new Thread(buy).start();
		new Thread(buy).start();
		new Thread(buy).start();
	}
}
class Buy implements Runnable {
	private int t=10;
	//定义Lock锁
	private final ReentrantLock l = new ReentrantLock();
	//加锁
	@Override
	public void run() {
		while(true) {
			try {
				l.lock();
				if(t>=0) {
					System.out.println(t);
					t--;
				}else {
					break;
				}
			}finally {
				l.unlock();
			}
			
		}
	}
}

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值