今天按毕老师视频写了代码,是一个死锁的,毕老师说可以运行一会后才会死锁,可 我试了10多次都是打印两行就死锁,我觉得代码有问题,代码如下,求大神分析,谢谢- class DeadLock
- {
- public static void main(String[] args)
- {
- Test t=new Test(true);
- Thread t1=new Thread(new Test(true));
- Thread t2=new Thread(new Test(false));
- //new Thread(t).start();
- t1.start();
- //t.flag=false;
- //new Thread(t).start();
- t2.start();
- }
- }
- class Test implements Runnable
- {
- public boolean flag;
- Test(boolean flag){
- this.flag=flag;
- }
- public void run(){
- while(true){
- if(flag){
- synchronized(MyLock.locka){
- System.out.println("if locka");
- synchronized(MyLock.lockb){
- System.out.println("if lockb");
- }
- }
- }else{
- synchronized(MyLock.lockb){
- System.out.println("else lockb");
- synchronized(MyLock.locka){
- System.out.println("else locka");
- }
- }
- }
- }
-
- }
- }
- class MyLock
- {
- static Object locka=new Object();
- static Object lockb=new Object();
- }
复制代码
|
|