标签:unsafe run i++ try rgs art 位置 lse inter
通过synchronized锁住保证线程的安全
//买票
public class SafeBuyTicket {
public static void main(String[] args) {
BuyTicket sation=new BuyTicket();
new Thread(sation,"买票的第一位").start();
new Thread(sation,"买票的第二位").start();
new Thread(sation,"买票的第三位").start();
}
}
class BuyTicket implements Runnable{
private int ticketNums=10;
boolean flag=true;
//线程关闭的标志位置
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException {
//锁的是this
if (ticketNums<=0){
flag=false;
return;
}
// 模拟延迟
// Thread.sleep(200);
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
用synchronized块锁住account(卡)
//两个不安全的取钱
public class SafeBank {
public static void main(String[] args) {
Account account=new Account(10000,"备用金");
Drawing you=new Drawing(account,50,"你");
Drawing girlFriend=new Drawing(account,100,"女朋友");
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;
}
@Override
public void run() {
// 默认锁的是this,这个程序中是bank;
// 但是需要锁account,锁bank并没用
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(this.getName()+"手里的钱:"+nowMoney);
}
}
}
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list=new ArrayList<String>();
for (int i = 0; i < 100000; i++) {
new Thread(()->{
//将list锁住就可以了
synchronized (list) {
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
参考自up主:狂神说Java
标签:unsafe run i++ try rgs art 位置 lse inter
原文地址:https://www.cnblogs.com/zouzhang/p/13202765.html