用两个线程,一个输出字母,一个输出数字,交替输出1A2B3C...
解法一(最优LockSupport)
static Thread t1 = null,t2 = null;
@Test
public void lockSupportTest() {
char[] a = "123456".toCharArray();
char[] b = "ABCDEF".toCharArray();
t1 = new Thread(() -> {
for (char c : a) {
System.out.println(c);
LockSupport.unpark(t2);
LockSupport.park();
}
},"t1");
t2 = new Thread(() -> {
for (char c : b) {
LockSupport.park();
System.out.println(c);
LockSupport.unpark(t1);
}
},"t2");
t1.start();
t2.start();
}
解法二(CAS)
static AtomicInteger status = new AtomicInteger(1);
@Test
public void casTest() {
char[] a = "123456".toCharArray();
char[] b = "ABCDEF".toCharArray();
new Thread(() -> {
for (char c : a) {
while (status.get() != 1) {}
System.out.println(c);
status.set(2);
}
},"t1").start();
new Thread(() -> {
for (char c : b) {
while (status.get() != 2) {}
System.out.println(c);
status.set(1);
}
},"t2").start();
}
解法三(synchronized)
@Test
public void synchronizedTest() {
final Object o = new Object();
char[] a = "123456".toCharArray();
char[] b = "ABCDEF".toCharArray();
new Thread(() -> {
synchronized (o){
for (char c : a) {
System.out.println(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"t1").start();
new Thread(() -> {
synchronized (o){
for (char c : b) {
System.out.println(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"t2").start();
}
解法四(ReentrantLock)
@Test
public void reentrantLockTest() {
Lock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();
char[] a = "123456".toCharArray();
char[] b = "ABCDEF".toCharArray();
new Thread(() -> {
try {
lock.lock();
for (char c : a) {
System.out.println(c);
c2.signal();
c1.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
},"t1").start();
new Thread(() -> {
try {
lock.lock();
for (char c : b) {
System.out.println(c);
c1.signal();
c2.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
},"t2").start();
}