线程不安全的小例子

本文通过三个示例展示了Java中线程不安全的问题,包括不安全的买票、不安全的取钱和线程不安全的集合。分别演示了在多线程环境下,如何通过`synchronized`关键字来确保代码的同步,解决并发安全问题。同时,对比了线程不安全的ArrayList和线程安全的CopyOnWriteArrayList在并发场景下的使用。
摘要由CSDN通过智能技术生成

1.

package ThreadTest.Day3;

/**
 * @author CCQ
 * 不安全的买票
 * 多个线程同时操作一个对象
 * synchronized关键字,锁住对象,避免同时操作一个对象
 */
public class Test01 {
    public static void main(String[] args) {
        buy b1 =new buy();

        new Thread(b1,"屌丝").start();
        new Thread(b1,"高富帅").start();
        new Thread(b1,"白富美").start();
    }
}


class buy implements Runnable{
    int num =10;
    boolean flag =true;
    @Override
    public void run() {
        while (flag){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buyk();
        }
    }

    public  void buyk(){
        if (num<=0){
            flag =false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"买到了"+num--);
    }
}

/*解决方法:在buyk方法前加入关键字synchronized
    public synchronized void buyk(){
        if (num<=0){
            flag =false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"买到了"+num--);
    }*/

2.

package ThreadTest.Day3;

/**
 * @author CCQ
 * 不安全的取钱
 * 两个人同时操作一个账户
 */
public class Test02 {
    public static void main(String[] args) {
        Account account =new Account(1000,"棋棋");
        bank b1 =new bank(account,1000);
        bank b2 =new bank(account,500);
        bank b3 =new bank(account,400);
        new Thread(b1,"瑶瑶").start();
        new Thread(b2,"杨杨").start();
        new Thread(b3,"KK").start();
    }
}

class Account{
    int money;//账户余额
    String name;//账户名字

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

class bank implements Runnable{
    Account account;
    int takemoney;//取多少钱
    int cash;//手里还有多少钱

    public bank(Account account, int takemoney) {
        this.account = account;
        this.takemoney = takemoney;
    }

    @Override
    public void run() {
            if (account.money-takemoney<0){
                System.out.println(account.name+"账户钱不够啦!");
                return;
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money =account.money-takemoney;
            cash =cash+takemoney;
            System.out.println(account.name+"账户的余额为:"+account.money);
            System.out.println(Thread.currentThread().getName()+"手里有现金:"+cash);
    }
}


/*解决方法:在run方法里加入synchronized代码块,锁住指定对象
    public void run() {
        synchronized(account){
            if (account.money-takemoney<0){
                System.out.println(account.name+"账户钱不够啦!");
                return;
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money =account.money-takemoney;
            cash =cash+takemoney;
            System.out.println(account.name+"账户的余额为:"+account.money);
            System.out.println(Thread.currentThread().getName()+"手里有现金:"+cash);
        }
    }

*/

3.

package ThreadTest.Day3;

import java.util.ArrayList;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 线程不安全的集合测试
 */
public class Test03 {
    public static void main(String[] args) {
        //线程不安全
        ArrayList<String> arrayList =new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                    arrayList.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(arrayList.size());
        /*解决方法:在lambda表达式里加入synchronized 代码块锁住指定对象
                    new Thread(()->{
                synchronized (arrayList){
                    arrayList.add(Thread.currentThread().getName());
                }
            }).start();*/


        //支持并发线程安全的集合
        CopyOnWriteArrayList<String> copyOnWriteArrayList =new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                copyOnWriteArrayList.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(copyOnWriteArrayList.size());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值