多线程的同步方法

2021-05-02 13:27

阅读:345

标签:unsafe   run   i++   try   rgs   art   位置   lse   inter   

多线程的同步方法

1.买票的例子

通过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

2.去银行取钱

用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

3.list

import java.util.ArrayList;
import java.util.List;

public class UnsafeList {
    public static void main(String[] args) {
        List list=new ArrayList();
        for (int i = 0; i {
                //将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


评论


亲,登录后才可以留言!