java中,通常用synchronized关键字对需要保证线程安全的代码块加锁,但是synchronized关键字在使用上并不灵活,而Lock锁刚好就可以解决这个问题。
面试中有可能会被要求写一个要求两个线程交替运行的程序,这里给出一个实现样例。
1、公共服务类
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadService {
private Lock lock = new ReentrantLock(false);
private Condition condition = lock.newCondition();
private volatile boolean flag = false;
public void executeTaskA() {
try{
lock.lock();
while (flag) {
condition.await();
}
flag = true;
System.out.println(Thread.currentThread().getName() + " : Task_A");
condition.signal();
}catch (InterruptedException exception) {
exception.printStackTrace();
}finally {
lock.unlock();
}
}
public void executeTaskB() {
try{
lock.lock();
while (!flag) {
condition.await();
}
flag = false;
System.out.println(Thread.currentThread().getName() + " : Task_B");
condition.signal();
}catch (InterruptedException exception) {
exception.printStackTrace();
}finally {
lock.unlock();
}
}
}
2、定义两个不同任务的线程
public class ThreadA extends Thread {
private ThreadService threadService;
public ThreadA(ThreadService threadService){
super();
this.threadService = threadService;
}
@Override
public void run() {
for(int i=0;i<100;i++){
threadService.executeTaskA();
}
}
}
public class ThreadB extends Thread {
private ThreadService threadService;
public ThreadB(ThreadService threadService){
super();
this.threadService = threadService;
}
@Override
public void run() {
for(int i=0;i<100;i++){
threadService.executeTaskB();
}
}
}
3、测试
public class Client {
public static void main(String[] args) {
ThreadService threadService = new ThreadService();
Thread threadA = new ThreadA(threadService);
Thread threadB = new ThreadB(threadService);
threadA.setName("Thread A");
threadB.setName("Thread B");
threadA.start();
threadB.start();
}
}
控制台输出: