- class TicketDemo4 implements Runnable {
- private int tickets = 100;
- Object obj = new Object();
- public void run() {
- while (true) {
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- }
- synchronized (obj) {
- if (tickets > 0) {
- System.out.println(Thread.currentThread().getName() + "卖出第:"+ (tickets--) + "张票");
-
- }
-
- }
- }
- }
- }
- class TicketDemoTest4 {
- public static void main(String[] args) throws Exception{
- TicketDemo4 td = new TicketDemo4();
-
- Thread t1 = new Thread(td,"窗口1:");
- Thread t2 = new Thread(td,"窗口2:");
- Thread t3 = new Thread(td,"窗口3:");
- Thread t4 = new Thread(td,"窗口4:");
-
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 你的要打印的代码放置的位置不对,应该放置在if{}体里面。我已经给你修改了,结果已经正确了。
|
|