在面试题中,我们经常会遇到这样的题目,线程依次交替执行,比如有三个线程,第一个线程打印1-2-3,第二个线程接着打印4-5-6,第三个线程打印7-8-9,再更换到线程一运行打印10-11-12,依此类推。或者只有两个线程,他们直接交替执行。
我们知道,默认情况下,多线程运行,资源是共享的,也就是说他们是竞争关系,谁得到cpu资源,谁就运行,其他线程等待,当运行完毕,接下来由谁运行,是不确定的,有可能还是刚才抢占过cpu资源的线程执行。
按照一些面试题的要求,我们需要资源按顺序分配,或者公平分配,而不是去争抢。如果是两个线程,可以考虑使用公平锁,这个很好解决,看代码:
package com.xxx.lock;
import java.util.concurrent.locks.ReentrantLock;
public class FairLockDemo {
public static void main(String[] args) {
Runnable target = new Runnable(){
private ReentrantLock lock = new ReentrantLock(true);
@Override
public void run() {
int i=10;
while (i>0) {
try{
lock.lock();
System.out.println(Thread.currentThread().getName()+"get lock.for loop "+i);
}finally{
lock.unlock();
}
i--;
}
}
};
Thread t1 = new Thread(target, "thread-1");
Thread t2 = new Thread(target, "thread-2");
t1.start();
t2.start();
}
}
运行结果:
thread-1 get lock.for loop 10
thread-2 get lock.for loop 10
thread-1 get lock.for loop 9
thread-2 get lock.for loop 9
thread-1 get lock.for loop 8
thread-2 get lock.for loop 8
thread-1 get lock.for loop 7
thread-2 get lock.for loop 7
thread-1 get lock.for loop 6
thread-2 get lock.for loop 6
thread-1 get lock.for loop 5
thread-2 get lock.for loop 5
t