线程同步
学习视频:【狂神说Java】多线程详解
up主:遇见狂神说
并发
同一个对象被多个线程同时操控
线程同步
线程同步实际上就是一种等待队列,多个需要同时访问此对象的线程进入这个对象的等待池 形成队列,等待前面线程使用完毕,下一个线程在使用
锁机制 synchronized
synchronized默认锁的是this
同步方法弊端
方法里需要修改的内容才需要锁,锁太多会造成资源浪费
同步块
示例:
package com.thread;
public class TestSymchronized {
public static void main(String[] args) {
Account account = new Account(1000,"结婚基金");
Drawing you = new Drawing(account,50,"you");
Drawing she = new Drawing(account,100,"she");
you.start();
she.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;
}
@Override
public void run() {
synchronized (account){
if (account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName()+"钱不够了");
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money =account.money-drawingMoney;
nowMoney = nowMoney+drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
System.out.println(Thread.currentThread().getName() + "手里的钱" + nowMoney);
}
}
}
死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。
某一个同步块同时拥有“两个以上的对象的锁”时,就可能发生死锁问题