定义两个线程,一个输出ABCD,一个输出1234,但是要求最终结果交替输出A1B2C3D4....
这貌似是个面试题,尝试写了下,方法应该很多。介绍几种写法:
/**
* 使用LockSupport交替输出A1B2C3....
*/
public class ByteNumber {
static Thread t1 = null;
static Thread t2 = null;
public static void main(String[] args) throws InterruptedException {
t1 = new Thread(new Runnable() {
public void run() {
for(char i=65;i<91;i++){
System.out.println(i);
LockSupport.unpark(t2);
LockSupport.park();
}
}
});
t2 = new Thread(new Runnable() {
public void run() {
for(int i=1;i<27;i++){
LockSupport.park();
System.out.println(i);
LockSupport.unpark(t1);
}
}
});
t1.start();
t2.start();
}
}
/**
* 使用Semaphore信号量交替输出A1B2C3....
*/
public class ByteNumber2 {
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore1 = new Semaphore(0);
final Semaphore semaphore2 = new Semaphore(0);
Thread t1 = new Thread(new Runnable() {
public void run() {
for(char i=65;i<91;i++){
try {
semaphore1.acquire();
System.out.println(i);
semaphore2.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for(int i=1;i<27;i++){
try {
semaphore1.release();
semaphore2.acquire();
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
}
/**
* 使用ReentrantLock信号量交替输出A1B2C3....
*/
public class ByteNumber3 {
public static void main(String[] args) throws InterruptedException {
final ReentrantLock lock = new ReentrantLock(true);
final Condition byteCon = lock.newCondition();
final Condition numCon = lock.newCondition();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
for(char i=65;i<91;i++){
System.out.println(i);
numCon.signal();
byteCon.await();
}
numCon.signal();
}catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
lock.lock();
for(int i=1;i<27;i++){
System.out.println(i);
byteCon.signal();
numCon.await();
}
byteCon.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
t1.start();
Thread.sleep(0);
t2.start();
}
}
/**
* 使用BlockingQueue信号量交替输出A1B2C3....
*/
public class ByteNumber6 {
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<String> b1 = new LinkedBlockingQueue<>(1);
final BlockingQueue<String> b2 = new LinkedBlockingQueue<>(1);
Thread t1 = new Thread(new Runnable() {
public void run() {
for(char i=65;i<91;i++){
try {
b2.take();
System.out.println(i);
b1.put("ok");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for(int i=1;i<27;i++){
try {
b2.put("ok");
b1.take();
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
}