面试中经常被遇到一个问题:现在有三个线程,分别执行会打印A,B,C,如何编码使得三个线程顺序执行,即输出‘ABCABC’,这道题看似简单,但是如果对多线程不熟悉或者没有准备还真的不好回答。
下面列举几种比较好理解的方法,代码手工编写,都已测试
lock和Synchronized都是通过线程间的通信,唤醒指定的线程实现顺序执行
1.使用lock
public class Task2Lock {
static Lock lock = new ReentrantLock();
static int count = 0;
static Condition condition1 = lock.newCondition();
static Condition condition2 = lock.newCondition();
static Condition condition3 = lock.newCondition();
/**
* 下面的while只是为了控制打印的次数
* @param args
*/
public static void main(String[] args) {
Thread tA = new Thread(() -> {
while (count < 4) {
//先获取锁
lock.lock();
//如果count取余3不等于0,就await
if (count % 3 != 0) {
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//否则就执行任务并count++,唤醒线程2
System.out.println("a");
count++;
condition2.signal();
lock.unlock();
}
});
Thread tB = new Thread(() -> {
while (count < 4) {
lock.lock();
if (count % 3 != 1) {
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("l");
count++;
condition3.signal();
lock.unlock();
}
});
Thread tC = new Thread(() -> {
while (count < 4) {
lock.lock();
if (count % 3 != 2) {
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("i");
count++;
condition1.signal();
lock.unlock();
}
});
tA.start();
tB.start();
tC.start();
}
}
2.使用Synchronized
static Object object = new Object();
static int count = 1;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 2; i++) {
synchronized (object) {
//注意这里要用while循环
while (count != 1) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a");
count = 2;
object.notifyAll();
}
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 2; i++) {
synchronized (object) {
while (count != 2) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("b");
count = 3;
object.notifyAll();
}
}
});
Thread t3 = new Thread(() -> {
for (int i = 0; i < 2; i++) {
synchronized (object) {
while (count != 3) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("c");
count = 1;
object.notifyAll();
}
}
});
t1.start();
t2.start();
t3.start();
}
还有下面这种写法,其实就是锁对象换成了this,我更喜欢上面的,逻辑清晰
public class TaskSynchronized {
public static void main(String[] args) {
PrintService printService = new PrintService();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 2; i++) {
printService.printA();
}
});
thread1.setName("A");
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 2; i++) {
printService.printB();
}
});
thread2.setName("B");
Thread thread3 = new Thread(() -> {
for (int i = 0; i < 2; i++) {
printService.printC();
}
});
thread3.setName("C");
thread2.start();
thread3.start();
thread1.start();
}
/**
* 里面的printA,printB,printC都必须加synchronized修饰
*/
static class PrintService {
private int flag = 1;
public synchronized void printA() {
while (flag != 1) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 2;
this.notifyAll();
}
public synchronized void printB() {
while (flag != 2) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 3;
this.notifyAll();
}
public synchronized void printC() {
while (flag != 3) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag = 1;
this.notifyAll();
}
}
}
3. 使用join
下面的代码只能输出一次ABC,暂时还没想到如何输出多次
public class TaskJoin {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(()->{
System.out.println("a");
});
Thread thread2 = new Thread(()->{
System.out.println("b");
});
Thread thread3 = new Thread(()->{
System.out.println("c");
});
//join方法会使得调用线程等待直到thread1结束die
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
}
}
join的作用是当前线程等待这个线程结束,底层实现就是循环判断isAlive(),不断的await。isAlive()是调用的系统本地方法
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
4.使用SingleThreadExecutor
public class Task2SingleThreadExecutor {
//利用并发包里的Excutors的newSingleThreadExecutor产生一个单线程的线程池,
// 而这个线程池的底层原理就是设置核心线程和最大线程都是1
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
System.out.println("a");
});
Thread thread2 = new Thread(()->{
System.out.println("b");
});
Thread thread3 = new Thread(()->{
System.out.println("c");
});
for (int i = 0; i < 2; i++) {
executorService.submit(thread1);
executorService.submit(thread2);
executorService.submit(thread3);
}
//作用是关闭线程池,终止线程执行
executorService.shutdown();
}
}
SingleThreadExecutor底层其实就是创建一个核心线程池为1,无界队列,最大线程为1的线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
5.使用信号量Semaphore
public class Task2Semaphore {
static Semaphore semaphore1 = new Semaphore(1);
static Semaphore semaphore2 = new Semaphore(1);
static Semaphore semaphore3 = new Semaphore(1);
static int count = 0;
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
while (count < 4){
try {
semaphore1.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//这里判断一次就可以控制执行的次数
System.out.println("a");
count++;
semaphore2.release();
}
});
Thread thread2 = new Thread(()->{
while (count < 4){
try {
//acquire方法会一直阻塞直到另一个线程释放他
semaphore2.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b");
count++;
semaphore3.release();
}
});
Thread thread3 = new Thread(()->{
while (count < 4){
try {
semaphore3.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("c");
count++;
semaphore1.release();
}
});
try {
//这里必须先获取semaphore2,semaphore3,阻止线程2,3运行。也就是必须有线程1先执行,并释放2的资源
semaphore2.acquire();
semaphore3.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
thread1.start();
thread3.start();
}
}
1196



被折叠的 条评论
为什么被折叠?



