java中多线程的线程同步死锁问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
}
}
以上是关于java中多线程的线程同步死锁问题的主要内容,如果未能解决你的问题,请参考以下文章