【Java开源代码栏目提醒】:网学会员为广大网友收集整理了,TextDeadLock.java,希望对大家有所帮助!
package com.zf.s14; //创建一个包
public class TextDeadLock { //操作线程死锁的类
static String[] chopsticks=new String []{"筷子1","筷子2"};
static class OneThread extends Thread{ //静态内部类
public void run(){
synchronized(chopsticks[0]){ //在同一时间只能有一个类访问
System.out.println("甲拿起了"+chopsticks[0]+",在等待另一"+chopsticks[1]);
try {
Thread.sleep(100); //线程休眠
} catch (Exception e) { //捕获异常
System.out.println("线程休眠出错:"+e.getMessage());
}
synchronized(chopsticks[1]){
System.out.println("甲又拿起了"+chopsticks[1]);
}
}
}
}
static class TwoThread extends Thread{ //静态内部类
public void run(){
synchronized(chopsticks[1]){
System.out.println("乙拿起了"+chopsticks[1]+",在等待另一"+chopsticks[0]);
try {
Thread.sleep(100); //线程休眠
} catch (Exception e) { //捕获异常
System.out.println("线程休眠出错:"+e.getMessage());
}
synchronized(chopsticks[0]){
System.out.println("乙又拿起了"+chopsticks[1]);
}
}
}
}
static class DaemonThread extends Thread{ //静态守护线程类
public DaemonThread(){
this.setDaemon(true); //线程设置守护
}
public void run(){
while(true){
try {
Thread.sleep(1000); //线程休眠
}catch (Exception e) { //捕获异常
System.out.println("线程休眠出错:"+e.getMessage());
}
System.out.println("守护线程:程序正在运行...");
}
}
}
public static void main(String []args){ //java程序主入口处
OneThread one=new OneThread(); //实例化对象
TwoThread two=new TwoThread();
DaemonThread daemon=new DaemonThread();
one.start(); //启动线程
two.start();
daemon.start();
}
}
上一篇:
TextCustomException.java
下一篇:
成本管理详细介绍