一道有趣的面试题
前面学习了多线程中的各种多线程工具类,还是锁的使用,下面来看一道有趣的面试题目,让大家有机会尝试使用前面的各种多线程工具类和锁
题目
请写一个程序,让两个线程交替输出“ABCDEF”和“123456”,输出结果为固定“A1B2C3D4E5F6”
解法
Talk is cheap, show me the code!!!
synchronized+wait/notify
public class sync_wait_notify {
public static void main(String[] args) {
final Object o = new Object();
char[] aI = "1234567".toCharArray();
char[] aC = "ABCDEFG".toCharArray();
new Thread(()->{
synchronized (o) {
for(char c : aI) {
System.out.print(c);
try {
o.notify();
o.wait(); //让出锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify(); //必须,否则无法停止程序
}
}, "t1").start();
new Thread(()->{
synchronized (o) {
for(char c : aC) {
System.out.print(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
}, "t2").start();
}
}
//如果我想保证t2在t1之前打印,也就是说保证首先输出的是A而不是1,这个时候该如何做?
condition
package com.mashibing.juc.c_026_00_interview.A1B2C3;
import java.lang.reflect.Array;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class T01_00_Question {
private char[] a1 = {'1','2','3','4','5','6'};
private char[] a2 = {'A','B','C','D','E','F'};
private ReentrantLock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
public void m1(){
int count = 0;
lock.lock();
while(count <= 4){
System.out.print(a2[count++]);
try {
c2.signal();
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
c2.signal();
lock.unlock();
}
public void m2(){
int count = 0;
lock.lock();
while(count <= 4){
System.out.print(a1[count++]);
try {
c1.signal();
c2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
c1.signal();
lock.unlock();
}
public static void main(String[] args) {
//要求用线程顺序打印A1B2C3....Z26
T01_00_Question t = new T01_00_Question();
new Thread(()->{
t.m1();
}).start();
new Thread(()->{
t.m2();
}).start();
}
}
LockSupport
import java.util.concurrent.locks.LockSupport;
//Locksupport park 当前线程阻塞(停止)
//unpark(Thread t)
public class T02_00_LockSupport {
static Thread t1 = null, t2 = null;
public static void main(String[] args) throws Exception {
char[] aI = "1234567".toCharArray();
char[] aC = "ABCDEFG".toCharArray();
t1 = new Thread(() -> {
for(char c : aI) {
System.out.print(c);
LockSupport.unpark(t2); //叫醒T2
LockSupport.park(); //T1阻塞
}
}, "t1");
t2 = new Thread(() -> {
for(char c : aC) {
LockSupport.park(); //t2阻塞
System.out.print(c);
LockSupport.unpark(t1); //叫醒t1
}
}, "t2");
t1.start();
t2.start();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。