線程Runnable
class 票子 implements Runnable {
private int bill = 0;
@Override
public void run() {
while (bill < 100) {
synchronized(Object.class){ //同步代碼塊 一次只能進入一個線程
if (bill < 100) {
bill++;
Thread thread = Thread.currentThread(); //獲取當前線程
System.out.println(thread.getName() + ": 第張" + bill-- + "票");
} else {
System.out.println("賣完了");
}
}
}
}
}
主程序:添加數據
public class 賣票 {
public static void main(String[] args) {
票子 piao=new 票子();
new Thread(piao,"1號牀").start();
new Thread(piao,"2號牀").start();
new Thread(piao,"3號牀").start();
}
}