并发案例
【小城贝尔】
经典并发小案例,买票取款和容器。
数据异常有原理,同时操作空间异。
买票抢票
class Web12306 implements Runnable{
private int tickets = 50;
@Override
public void run() {
while (tickets > 0) {
this.sellTickets();
}
}
public void sellTickets(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +"========>>"+(this.tickets--));
}
/*
因为每个线程都有自己的工作空间 从主存中拷贝值操作然后在赋值回去
美团========>>0
飞猪========>>-1
同时拿到了相同的值
飞猪========>>37
美团========>>37
*/
}
class Web12306Test{
public static void main(String[] args) {
Web12306 web = new Web12306();
new Thread(web , "美团").start();
new Thread(web , "携程").start();
new Thread(web , "飞猪").start();
new Thread(web , "去哪儿").start();
}
}
取款
/*******************************取款************************************************************/
class Account {
int balance;
String userName;
public Account(int balance, String userName) {
this.balance = balance;
this.userName = userName;
}
}
class AutoBank implements Runnable{
Account account;
int getMoney;
public AutoBank(Account account, int getMoney) {
this.account = account;
this.getMoney = getMoney;
}
@Override
public void run() {
this.getMoney();
}
public void getMoney(){
if (account.balance - getMoney <= 0) {
System.out.println("余额不足 。。。。你的余额是 ==》 " + account.balance + " 您想取 : " + getMoney);
return;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.balance = (account.balance - getMoney);
System.out.println("取出 : " + this.getMoney + " : 剩下 :" + account.balance);
}
/*
取出 : 80 : 剩下 :20
取出 : 70 : 剩下 :-50
*/
}
class AutoBankTest{
public static void main(String[] args) {
Account account = new Account(100,"小城贝尔");
AutoBank ab = new AutoBank(account , 80);
new Thread(ab).start();
AutoBank ab1 = new AutoBank(account , 70);
new Thread(ab1).start();
}
}
容器
/********************************容器**********************************/
class Collectios {
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();
}
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("list size is ==> "+list.size());
for(int i = 0; i < 100;i ++){
System.out.println("value ==> "+list.get(i));
}
}
}