a12053094 2011-06-22 15:47
浏览 195
已采纳

关于lock应用的问题

今天使用 lock方法时候,发现lock如果new的位置也需要将就,否则无效,查了资料好像也没有这方便的,一知半解求教:
代码如下:
public class Test {
int type=0;
//private Lock l = new ReentrantLock(); 位置 A
public class ThreadOne implements java.lang.Runnable{
Lock l=new ReentrantLock(); //位置 B
public void run(){

l.lock();
try{
for(int i=0;i<10;i++){
type++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{

            }
            System.out.println(type+"******"+ i+"===="+Thread.currentThread().getName());

           }
    }finally{
        l.unlock();
     }
        }

}

public static void main(String[] args){     
    Test t=new Test();      

    ThreadOne tOne= t.new ThreadOne();
    ThreadOne two=t.new ThreadOne();



    for(int i=0;i<1;i++){
        Thread t1=new Thread(tOne);
        Thread t2=new Thread(two);
        t1.start();
        t2.start();
    }       
}   

}

如果LOCK在位置A new 的时,执行结果如下:
1******0====Thread-0
2******1====Thread-0
3******2====Thread-0
4******3====Thread-0
5******4====Thread-0
6******0====Thread-1
7******1====Thread-1
8******2====Thread-1
9******3====Thread-1
10******4====Thread-1
如果lock在位置B new 的时候,执行结果如下:
2******0====Thread-0
3******0====Thread-1
4******1====Thread-0
5******1====Thread-1
6******2====Thread-0
7******2====Thread-1
8******3====Thread-0
9******3====Thread-1
10******4====Thread-0
10******4====Thread-1

说明在B的时候,锁是失效的;不知道是什么原因,还请明白的给小弟说说

问题补充:如果在MAIN方法里面,线程调用时候:
Thread t1=new Thread(tOne);
Thread t2=new Thread(tOne);即调用同一个runnable的时候,执行结果是:
1******0====Thread-0
2******1====Thread-0
3******2====Thread-0
4******3====Thread-0
5******4====Thread-0
6******0====Thread-1
7******1====Thread-1
8******2====Thread-1
9******3====Thread-1
10******4====Thread-1
这又是为什么呢?

  • 写回答

1条回答 默认 最新

  • 也许世界还没停 2011-06-22 16:12
    关注

    lock在A位置时,两个线程公用一个锁对象
    在B位置时,两个线程就是两把锁了,各自有一把
    所有没有起到同步的作用

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog