java中多线程的线程同步死锁问题

/*

*定义一个多线程

*/

package com.thread;

public class TicketThread2 implements Runnable {

//定义1000张票
public static int ticket = 100;

Object obj = new Object();

//
public boolean flag = false;

//
public boolean exit = false;

@Override
public void run() {
// TODO Auto-generated method stub

  if(flag){
    while(true){
      synchronized (obj) {
        show();
      }
    }
  }else{
    while(true){
      show();
    }
  }

  //为什么不直接用下面这个死循环
  /*while(true){
     show();
    }*/
}

//售票
public synchronized void show(){
    synchronized (obj) {
      if(ticket > 0){
        try {
            Thread.sleep(10);
            System.out.println(Thread.currentThread().getName()+”\t剩余票数:”+ ticket–);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //System.out.println(Thread.currentThread().getName()+”\t剩余票数:”+ ticket–);
      }
    }
}

}

 

/*

*启动多线程

*/

package com.test;

import java.lang.reflect.Field;

import com.thread.TicketThread2;

public class TestTicketThread2 {

public static void main(String[] args) {
  // TODO Auto-generated method stubs

  TicketThread2 tt = new TicketThread2();

  Thread t1 = new Thread(tt,”线程1″);
  Thread t2 = new Thread(tt,”线程2″);

  Thread t3 = new Thread(tt,”线程3″);

  t1.start();

  //主线程休眠:100秒
  /*try {
  Thread.sleep(100);
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }*/

  //改变多线程中flag的值
  tt.flag = !tt.flag;

  //
  t2.start();

  t3.start();

  }

}

    原文作者:咳,你的鞋带散了
    原文地址: http://www.cnblogs.com/linghongsan/p/5854240.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞