多线程死锁:对资源进行等级排序
将关键代码区设置为synchronized,即同一时刻只能有一个线程执行,
package deadlock;
import java.util.concurrent.TimeUnit;
public class ThreadDemo5
{
public static Integer r1 = 1;
public static Integer r2 = 2;
public static void main(String args[]) throws InterruptedException
{
TestThread51 t1 = new TestThread51();
t1.start();
TestThread52 t2 = new TestThread52();
t2.start();
}
}
class TestThread51 extends Thread
{
public void run()
{
//先要r1,再要r2
synchronized(ThreadDemo5.r1)
//括号中的参数是锁的对象,谁先抢到这个对象,谁来执行这块代码
{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(ThreadDemo5.r2)
{
System.out.println("TestThread51 is running");
}
}
}
}
class TestThread52 extends Thread
{
public void run()
{
//先要r2,再要r1
synchronized(ThreadDemo5.r1)
{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(ThreadDemo5.r2)
{
System.out.println("TestThread52 is running");
}
}
}
}
守护线程:与main函数共存亡的线程,守护线程的生存期是当其run方法执行完毕后或者main函数执行完毕后,不建议用守护线程来打开文件和数据库等
package daemon;
public class ThreadDemo4
{
public static void main(String args[]) throws InterruptedException
{
TestThread4 t = new TestThread4();
t.setDaemon(true);//将该线程设为守护线程
t.start();
Thread.sleep(2000);
System.out.println("main thread is exiting");
}
}
class TestThread4 extends Thread
{
public void run()
{
while(true)
{
System.out.println("TestThread4" +
" is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}