一 代码实操
1.1 资源
public class ObjectTools { public static Object folk=new Object(); public static Object chlk=new Object(); }
1.2 子线程
线程1:
public class ThreadA implements Runnable {
@Override
public void run() {
synchronized (ObjectTools.chlk){
System.out.println("线程:"+Thread.currentThread().getName()+" 获取筷子了!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (ObjectTools.folk){
System.out.println("线程:"+Thread.currentThread().getName()+" 获取叉子了!");
}
}
}
}
线程2:
public class ThreadB implements Runnable {
@Override
public void run() {
synchronized (ObjectTools.folk){
System.out.println("线程:"+Thread.currentThread().getName()+" 获取叉子了!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (ObjectTools.chlk){
System.out.println("线程:"+Thread.currentThread().getName()+" 获取筷子了!");
}
}
}
}
1.3 调用类
public class TestDl { public static void main(String[] args) { new Thread(new ThreadA()).start(); new Thread(new ThreadB()).start(); } }
1.4 结果
1.通过 jps 查看pid ;2.通过jstack -l pid 进行排查