不多说,直接上代码:
package com.loan.common.utils;
/**
* @author herman
*
*/
public class testThread {
public static void main(String[] args) {
Ticket ticket = new Ticket();
Thread t1 = new Thread(ticket,"窗口一:");
Thread t2 = new Thread(ticket,"窗口二:");
Thread t3 = new Thread(ticket,"窗口三:");
t1.start();
t2.start();
t3.start();
}
}
package com.loan.common.utils;
public class Ticket implements Runnable {
private int tickets = 100;
public void run() {
while (tickets > 0) {
synchronized (Ticket.class) {
if (tickets > 0) {
tickets--;
System.out.println(Thread.currentThread().getName() + "正在卖票,还剩下" + tickets + "张");
}
}
try {
// 休眠一秒,让执行的效果更明显
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
1968

被折叠的 条评论
为什么被折叠?



