1、多线程并发注意线程安全
synchronized`
package thread;
public class Train {
private int number ;
public Train(int number){
this.number=number;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public void buttocked(int count){
synchronized (this) {
int count1 = this.number - count;
this.setNumber(count1);
System.out.println("购买1张车票成功,剩余" + this.getNumber());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package thread;
public class TrainThread extends Thread {
private Train account ;
public void run(){
//每次购买1张车票
account.buttocked(1);
}
//传参设定总车票数
public TrainThread(Train account) {
this.account = account;
}
}
package thread;
public class TrainTest01 {
public static void main(String[] args) {
int i = 100 ;
//设定总共车票数
Train a1 = new Train(100);
while (i>0){
new TrainThread(a1);
(new TrainThread(a1)).start();
i--;
}
}
}