您的位置:首页 > 编程语言 > Java开发

Java多线程Lock对象常用方法(4)

2016-02-27 16:48 316 查看
Lock对象最后一个方法,tryLock()方法

这个方法的作用是,检查当前lock是否被其他线程持有,如果是,则不持有,如果不是,则持有。看效果。

package com.lenovo.plm.dms.p24;

import java.util.concurrent.locks.ReentrantLock;

public class Service {

public ReentrantLock lock = new ReentrantLock();

public void service(){
if(lock.tryLock()){
System.out.println(Thread.currentThread().getName() + "  get locked");
}else{
System.out.println(Thread.currentThread().getName() + "  does not get locked");
}
}

public void service2(){

lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " get lock..");
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
package com.lenovo.plm.dms.p24;

public class Main {
public static void main(String[] args) {
final Service service = new Service();

Runnable runnable2 = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
service.service2();
}
};
Thread threadC  = new Thread(runnable2);
threadC.start();
Runnable runnable = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
service.service();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread threadA = new Thread(runnable);
threadA.setName("A");
threadA.start();
Thread threadB = new Thread(runnable);
threadB.setName("B");
threadB.start();
}
}


运行结果如下:

Thread-0 get lock..

A does not get locked

B does not get locked

A does not get locked

B does not get locked

A does not get locked

B does not get locked

A does not get locked

B does not get locked

A does not get locked

B does not get locked

A get locked

B does not get locked

A get locked

B does not get locked

A get locked

B does not get locked

A get locked

B does not get locked

A get locked

B does not get locked

A get locked

B does not get locked

A get locked

B does not get locked
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 多线程