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而且有时得到正确的结果 有时候不是正确的。。 谁知道为什么?
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而且有时得到正确的结果 有时候不是正确的。。 谁知道为什么?
解决方案 »
- 求解if (input.hasNextDouble()==true)什么意思
- noclassdeffounderror
- 坐等高手解答
- 什么时候、什么情况下必须要return?也就是什么时候要返回值?
- 新手题 求解
- 菜鸟提问
- 关于java函数取模 ============================================满分====在线等待
- 请问如何用java获得图片文件的相关信息(文件大小,图片尺寸,像素等),图片格式为jpg,gif,bmp等
- 谁晓得这是什么软件画出来的类图
- setIcon(new ImageIcon("1.bmp"))不加载图像,求助
- 关于IO中FileInputStream流,以下代码抛异常。
- 关于《think in java》中的泛型数组(关于擦除的问题) 求大牛指教!!!
直接运行的话 没办法控制main方法这个线程
所以两个线程的运行顺序是没办法控制的。
所以就出现一阵正确一阵错误的情况。但是打了断点之后 就一步一步的进行 就可以按照代码中所写的那样的顺序来执行了
小弟这么理解也不知道对不对。
可以控制,就看你想怎么控制,可以sleep让出cpu让某个线程先执行,也可以用flag的方式,如果还轮不到自己运行,就wait让其他线程运行