本帖最后由 liuhao_hm 于 2015-7-12 22:35 编辑
- class Ticket implements Runnable
- {
- private int num = 100;
- boolean flag = true;
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(this)
- {
- if(num>0)
- {
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e)
- {
- }
- System.out.println(Thread.currentThread().getName()+"..."+num--);
- }
- }
- }
- }
- else
- {
- while(true)
- {
- show();
- }
- }
- }
- public synchronized void show()
- {
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e)
- {
- }
- System.out.println(Thread.currentThread().getName()+"..show.."+num--);
- }
- }
- class SynFunctionLockDemo
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- t1.start();
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e )
- {
- }
- t.flag = false;
- t2.start();
- }
- }
复制代码
重写了N遍,只有一次运行的时候没有出现负数,其余都是运行的时候出现负数,实在找不到问题的所在了 |
|