synchronized對象所
用在方法上鎖的是this或class
利用synchronized塊來自定義鎖的對象
一定要判斷好要鎖住哪個對象
樣例一掸驱,用在方法上鎖住this對象
package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: AsyncTest1
* @author:
* @description: 線程不安全示例1
* @date: 2021/12/7 23:54
*/
public class AsyncTest1 {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket, "程序員").start();
Thread thread1 = new Thread(ticket, "黃牛");
thread1.setPriority(1);
Thread thread = new Thread(ticket, "學(xué)生");
thread.setPriority(10);
thread1.start();
thread.start();
}
}
class Ticket implements Runnable {
private int ticketNum = 10;
private boolean flag = true;
@Override
public void run() {
while (flag) {
buyTicket();
}
}
private synchronized void buyTicket() {
if (ticketNum <= 0) {
flag = false;
return;
}
System.out.println(Thread.currentThread().getName() + "購買第" + ticketNum + "票!");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketNum--;
}
}
樣例二:加入synchronized塊自定義上鎖對象
package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: UnsafeBank
* @author:
* @description: 多個提款機取票昼榛,觀察最終的賬戶余額和到手金額
* @date: 2021/12/8 10:33
*/
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account("工資卡", 100);
CashMachine cashMachine1 = new CashMachine(account, 100);
CashMachine cashMachine = new CashMachine(account, 50);
new Thread(cashMachine, "張三").start();
new Thread(cashMachine1, "張三老婆").start();
}
}
class Account {
// 卡明
private String name;
// 卡內(nèi)余額
private int money;
public Account(String name, int money) {
this.name = name;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
class CashMachine implements Runnable {
private Account account;
// 共計取出的金額
private int nowMoney;
// 提款機中取出的金額
private int getMoney;
public CashMachine(Account account, int getMoney) {
this.account = account;
this.getMoney = getMoney;
}
@Override
public void run() {
synchronized (account){
if (this.account.getMoney() - getMoney < 0) {
System.out.println(Thread.currentThread().getName() + "卡里余額不足!");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.draw();
}
}
private void draw() {
// 卡內(nèi)余額
int temp = this.account.getMoney() - getMoney;
this.account.setMoney(temp);
// 手里
this.nowMoney = this.nowMoney + getMoney;
System.out.println(Thread.currentThread().getName() + "取出" + getMoney + "元,賬戶余額" + temp + "元茁帽,共計到手" + this.nowMoney + "元");
}
}