今天使用 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
这又是为什么呢?