static Thread t1 = null;
static Thread t2 = null;
char[] char1 = "123456".toCharArray();
char[] char2 = "ABCDEF".toCharArray();
t1 = new Thread(() -> {
for (char c : char1) {
System.out.println(c);
LockSupport.unpark(t2);
LockSupport.park();
}
}, "t1");
t2 = new Thread(() -> {
for (char c : char2) {
LockSupport.park();
System.out.println(c);
LockSupport.unpark(t1);
}
}, "t2");
t1.start();
t2.start();
char[] char1 = "123456".toCharArray();
char[] char2 = "ABCDEF".toCharArray();
Object o = new Object();
new Thread(() -> {
synchronized (o) {
for (char c : char1) {
System.out.println(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
o.notify();
}
}, "t1").start();
new Thread(() -> {
synchronized (o) {
for (char c : char2) {
System.out.println(c);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
o.notify();
}
}, "t2").start();
ReentrantLock lock = new ReentrantLock();
Condition conditionT1 = lock.newCondition();
Condition conditionT2 = lock.newCondition();
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
lock.lock();
try {
for (char c : char2) {
System.out.println(c);
conditionT2.signal();
conditionT1.await();
}
conditionT2.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}, "t1").start();
new Thread(() -> {
lock.lock();
try {
for (char c : char1) {
System.out.println(c);
latch.countDown();
conditionT1.signal();
conditionT2.await();
}
conditionT1.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}, "t2").start();
LinkedTransferQueue<Object> queue = new LinkedTransferQueue<>();
new Thread(() -> {
try {
for (char c : char1) {
queue.transfer(c);
System.out.println(queue.take());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "t1").start();
new Thread(() -> {
try {
for (char c : char2) {
System.out.println(queue.take());
queue.transfer(c);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "t2").start();