線程非同步的代碼
/*
?* 取錢線程不安全
?*/
public class UnsafeTest02 {
?? ?public static void main(String[] args) {
?? ??? ?//賬戶
?? ??? ?Account account=new Account(100,"結婚禮金");
?? ??? ?Drawing you=new Drawing(account,80,"可悲的你");
?? ??? ?Drawing wife=new Drawing(account,90,"happy的她");
?? ??? ?you.start();
?? ??? ?wife.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;//取的錢數(shù)
?? ?int packetTotal;//口袋的錢
?? ?
?? ?public Drawing(Account account, int drawingMoney,String name) {
?? ??? ?super(name);
?? ??? ?this.account = account;
?? ??? ?this.drawingMoney = drawingMoney;
?? ?}
?? ?@Override
?? ?public void run() {
?? ??? ?if(account.money-drawingMoney<0) {
?? ??? ??? ?return;
?? ??? ?}
?? ??? ?try {
?? ??? ??? ?Thread.sleep(1000);
?? ??? ?} catch (InterruptedException e) {
?? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?? ??? ?account.money-=drawingMoney;
?? ??? ?packetTotal+=drawingMoney;
?? ??? ?System.out.println(this.getName()+"-->賬戶余額為:"+account.money);
?? ??? ?System.out.println(this.getName()+"-->口袋的錢為:"+packetTotal);
?? ?}
}
package cn.jd.syn;
/*
?* 線程不安全:數(shù)據(jù)有負數(shù)還有相同的情況
?*/
public class UnsafeTest01 {
?? ?public static void main(String[] args) {
?? ??? ?//一份資源
?? ??? ?UnsafeWeb12306? web=new UnsafeWeb12306();
?? ??? ??? ??? ?//多個代理
?? ??? ??? ??? ?new Thread(web,"laoda").start();
?? ??? ??? ??? ?new Thread(web,"laoer").start();
?? ??? ??? ??? ?new Thread(web,"laosan").start();
?? ?}
}
class UnsafeWeb12306 implements Runnable{
?? ?//票數(shù)
?? ?private int ticketNums=3;
?? ?private boolean flag=true;
?? ?@Override
?? ?public void run() {
?? ??? ?while(flag) {
?? ??? ??? ?test();
?? ??? ?}
?? ??? ?
?? ?}
?? ?public void test() {
?? ??? ?if(ticketNums<0) {
?? ??? ??? ?flag=false;
?? ??? ??? ?return;
?? ??? ?}
?? ??? ?//模擬網(wǎng)絡延時
?? ??? ?try {
?? ??? ??? ?Thread.sleep(200); ?
?? ??? ??? ?//進入了阻塞狀態(tài),然后200s以后我就重新等待CPU的調用
?? ??? ??? ?//繼續(xù)執(zhí)行下面的代碼
?? ??? ?} catch (InterruptedException e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?? ??? ?System.out.println(Thread.currentThread().getName()+"-->"+ticketNums--);
?? ?}
?? ?
}
package cn.jd.syn;
import java.util.ArrayList;
import java.util.List;
/*
?* 取錢線程不安全
?* 操作容器
?*/
public class UnsafeTest03 {
?? ?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());? //發(fā)現(xiàn)有些數(shù)據(jù)丟掉了,顯然是被覆蓋了
?? ?}
}
標簽: