以下是代码:- package thread;
- public class Ticket3 implements Runnable
- {
- private int tick=100;
- Object obj=new Object();
- boolean flag=true;
- @Override
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(this)
- {
- if(tick>0)
- {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- System.out.println(Thread.currentThread().getName() + "....code:"+ tick--);
- }
- }
- }
- else
- while(true)
- show();
- }
- public synchronized void show()
- {
- if (tick > 0) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- System.out.println(Thread.currentThread().getName() + "....show:"+ tick--);
- }
- }
- }
复制代码- package thread;
- public class ThisLockDemo2
- {
- public static void main(String[] args)
- {
- Ticket3 t=new Ticket3();
- Thread t1=new Thread(t);
- Thread t2=new Thread(t);
- t1.start();
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- t.flag=false;
- t2.start();
- }
- }
复制代码 下面是我用MyEclipse打印的结果,竟然出现负数,找了半天不知是哪里出错了,吓人:
Thread-1....show:2
Thread-1....show:1
Thread-0....code:0
Thread-0....code:-1
Thread-0....code:-2
|
|