Requirements:
There are two strings:
String a = “”1234567”; String b = “ABCDEFG”
Use two threads T1 and T2 to print strings A and B, respectively. Enable it to output alternately: 1A2B3C4D5E6F7G
Solution:
- Here using juC under the tool class: LockSupport, show thread straight line communication, that is direct, and violence!
- Data sources:
private Thread t1;
private Thread t2;
private char[] aI = "1234567".toCharArray();
private char[] aC = "ABCDEFG".toCharArray();
Copy the code
- Ideas and concrete implementation
public void test3(a) {
t1 = new Thread(new Runnable() {
@Override
public void run(a) {
for (char c : aI) {
// Just print a character
System.out.print(c);
// Unlock T2 immediately
LockSupport.unpark(t2);
// Lock yourselfLockSupport.park(); }}}); t2 =new Thread(new Runnable() {
@Override
public void run(a) {
for (char c : aC) {
// Lock yourself up to prevent yourself from printing first
LockSupport.park();
// unlocked by T1, start printing a character
System.out.print(c);
// Unlock the T1 thread so that T1 can continue printingLockSupport.unpark(t1); }}}); t1.start(); t2.start(); }Copy the code