Thread:多線程 實現簡單購票
package com.heima.it;
public class duoXiCheng extends Thread{
//繼承Thread類
//定義一個票數的變量 static 靜態的 公用的 票數
static int tickets = 100;
//
public duoXiCheng() {
super();
// TODO 自動生成的構造函數存根
}
public duoXiCheng(String name) {
super(name);
// TODO 自動生成的構造函數存根
//構造一個有參數的方法傳遞一個名字進來
}
[email protected]
public void run() {
// TODO 自動生成的方法存根
//重寫run()方法
while(true){
//synchronized 加鎖 格式: 字節碼文件
synchronized (duoXiCheng.class) {
//3.創建 Thread 類的子類的對象,
if(tickets<1){
//票數少於1張退出循環
break;
}
try {
//暫停100毫秒
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
//多線程輸出語句
System.out.println(getName()+"正在出售第"+ (tickets--) +"票");
}
}
//程序結束
}
}
}
}
/**************************************************************************************************************************/
package com.heima.it;
public class pingTai {
public static void main(String[] args) {
// TODO 自動生成的方法存根
duoXiCheng dxc = new duoXiCheng("窗口1:");
dxc.start();
duoXiCheng dxc2 =new duoXiCheng("窗口2:");
dxc2.start();
duoXiCheng dxc3 =new duoXiCheng("窗口3:");
dxc3.start();
}
}
Thread:多線程 實現簡單購票