线程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();
}
}