package com.jit.test;import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;public class AttemptLocking { private ReentrantLock lock = new ReentrantLock(); public void untimed() {
boolean captured = lock.tryLock();
try {
System.out.println("tryLock(): " + captured);
} finally {
if (captured)
lock.unlock();
}
} public void timed() {
boolean captured = false;
try {
captured = lock.tryLock(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException();
}
try {
System.out.println("tryLock(2,TimeUnit.SECONDS): " + captured);
} finally {
if (captured)
lock.unlock();
}
} public static void main(String[] args) {
final AttemptLocking al = new AttemptLocking();
al.untimed();
al.timed(); 
new Thread() {

setDaemon(true);
} public void run() {
al.lock.lock();
System.out.println("Acquired");
}
}.start();
Thread.yield();
al.untimed();
al.timed();
}
}源码如上
我打断点debug以后的运行结果是:
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
Acquired
tryLock(): false
tryLock(2,TimeUnit.SECONDS): false
但是正常直接run as java application后的结果:
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
Acquired而且有时得到正确的结果 有时候不是正确的。。 谁知道为什么?

解决方案 »

  1.   

    哈哈 自己想明白怎么回事了。
    直接运行的话 没办法控制main方法这个线程
    所以两个线程的运行顺序是没办法控制的。
    所以就出现一阵正确一阵错误的情况。但是打了断点之后 就一步一步的进行 就可以按照代码中所写的那样的顺序来执行了
     小弟这么理解也不知道对不对。
      

  2.   

    但是这个用Lock 锁 可以像synchronized那样用wait 和notify嘛?
      

  3.   

    就是说java本身的机制就是 有些情况的并发是没 办法完全控制的 对吗?
      

  4.   

    当然不是,完全取决于你打算怎么控制。即便是启动函数start(),也是你自己去主动调用的啊
      

  5.   


    可以控制,就看你想怎么控制,可以sleep让出cpu让某个线程先执行,也可以用flag的方式,如果还轮不到自己运行,就wait让其他线程运行