java 多线程-线程不安全案例
发布时间:2020-12-15 08:24:09 所属栏目:Java 来源:网络整理
导读:抢票案例: public class n {public static void main(String[]args) throws InterruptedException{ web wb=new web(); new Thread(wb,"a").start(); new Thread(wb,"b").start(); new Thread(wb,"c").start();}}class web implements Runnable{int num=10;pr
抢票案例:
public class n { public static void main(String[]args) throws InterruptedException { web wb=new web(); new Thread(wb,"a").start(); new Thread(wb,"b").start(); new Thread(wb,"c").start(); } } class web implements Runnable{ int num=10; private boolean flag=true; public void run() { while(flag) { test(); } } public void test() { if(num<0) { flag=false; return; } try { Thread.sleep(200); }catch(InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"-->"+num--); //线程不安全,可能都都是同一张票,可能票是负数 //负数:当还有1张票时,三个线程同时进入,都等待后,有两个线程为负数 //相同票:线程有自己的工作台,多个线程几乎同时到达,拷贝数据 } } 账户存取款案例: public class el { public static void main(String[]args) { account a=new account(100,"me"); get g=new get(a,80,"she"); get g2=new get(a,90,"he"); g.start(); g2.start(); } } //账户 class account { int money; String name; public account(int money,String name) { this.money=money; this.name=name; } } //模拟取款 class get extends Thread { account a; //取钱的账户 int getmoney; //单个人取的钱数 int getall; //多个人取的总数 public get (account a,int getmoney,String name) { super(name);//Thread可以设置name this.a=a; this.getmoney=getmoney; } public void run() { if(a.money-getmoney<0) //添加也没用 { return; } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } a.money-=getmoney; getall+=getmoney; System.out.println(this.getName()+"-->账户余额为:"+a.money); System.out.println(this.getName()+"-->取钱总数为:"+getall); } } 操作容器案例: public class h { public static void main(String[]args) { List<String> list=new ArrayList<String>(); for(int i=0;i<10000;i++) { new Thread(()-> {list.add(Thread.currentThread().getName());} ).start(); } System.out.println(list.size()); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |