码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-09-08 19:57:44      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

/*

*定义一个多线程

*/

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();


  }

}

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

标签:

原文地址:http://www.cnblogs.com/linghongsan/p/5854240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!