标签:pac 性能 方法 syn dead turn 银行 多线程同步 tar
当多个线程访问同一个对象,并且线程还想修改对象,这时候就需要线程同步,线程同步其实就是一个等待机制,多个需要访问此对象的线程进入对象的等待池形成队列,等待前一个线程使用完毕,下一个线程再使用。
public synchronized void method(){}
package syn;
//不安全取钱
//两个人去银行取钱
//银行需要账户
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(1000,"结婚基金");
Drawing you = new Drawing(account,50,"你");
Drawing girl = new Drawing(account,100,"你老婆");
you.start();
girl.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) {
}
account.money = account.money-drawingMoney;
nowMoney = nowMoney +drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(Thread.currentThread().getName()+"手里的钱:"+nowMoney);
}
}
}
package syn;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0, "灰姑娘");
Makeup g2 = new Makeup(1, "白雪公主");
g1.start();
g2.start();
}
}
//口红
class Lipstick {
}
//镜子
class Mirror {
}
class Makeup extends Thread {
//需要的资源,只有一份(static保证唯一)
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choise; //选择
String girlName;//使用化妆品的人
Makeup(int choise, String girlName) {
this.choise = choise;
this.girlName = girlName;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
}
}
//互相持有对方的锁(需要拿到对方的资源)
private void makeup() throws InterruptedException {
if (choise == 0) {
synchronized (lipstick) {
//口红的锁
System.out.println(this.girlName + "获得了口红的锁");
Thread.sleep(1000);
synchronized (mirror) {//一秒钟后获得了镜子
//镜子的锁
System.out.println(this.girlName + "获得了镜子的锁");
}
}
} else {
synchronized (mirror) {
//镜子的锁
System.out.println(this.girlName + "获得了镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) {//一秒钟后获得了口红
//口红的锁
System.out.println(this.girlName + "获得了口红的锁");
}
}
}
}
}
只要解决以上一条即可避免死锁(锁不能嵌套锁!)
ReentrantLock(可重入锁)类实现了Lock
class A {
private final ReentrantLock lock = new ReenTrantLock();
public void m(){
lock.lock();//上锁
try{
//保证线程安全的代码
}finally{
lock.unlock();//开锁
}
}
}
标签:pac 性能 方法 syn dead turn 银行 多线程同步 tar
原文地址:https://www.cnblogs.com/sxblogs/p/12896724.html