方法一、LockSupport
public class TestD3 {
static Thread t1 = null;
static Thread t2 = null;
public static void main(String[] args) {
TestD3 t = new TestD3();
String[] strs = new String[]{"A","B","C","D","E","F","G","H",
"I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
};
t1 = new Thread(() -> {
for (String str :strs) {
System.out.print(str);
LockSupport.unpark(t2);
LockSupport.park();
}
},"T1");
t2 = new Thread(() -> {
for (int i = 1; i <= 26; i++) {
LockSupport.park();
System.out.print(i);
LockSupport.unpark(t1);
}
},"T2");
t1.start();
t2.start();
}
}
方法二、wait()和notify()
有瑕疵,无法确保t1在t2之前执行,可能会出现1A2B...26Z
public class TestD1 {
public static void main(String[] args) {
final Object o = new Object();
String[] strs = new String[]{"A","B","C","D","E","F","G","H",
"I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
};
Thread t1 = new Thread(() -> {
synchronized (o) {
for (String str :strs) {
System.out.print(str);
try {
o.notify();//唤醒T2
o.wait();//T1释放锁,T2执行
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
o.notify();
}
}
}
},"T1");
Thread t2 = new Thread(() -> {
synchronized (o) {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= 26; i++) {
System.out.print(i);
o.notify();//唤醒T1
if (i<26){
try {
o.wait();//释放锁,让T1执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
},"T2");
t1.start();
t2.start();
}
}
方法三、ReentrantLock
有瑕疵,无法确保t1在t2之前执行,可能会出现1A2B...26Z
public class TestD2 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition lockT1 = lock.newCondition();
Condition lockT2 = lock.newCondition();
String[] strs = new String[]{"A","B","C","D","E","F","G","H",
"I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
};
Thread t1 = new Thread(() -> {
lock.lock();
try {
for (String str :strs) {
System.out.print(str);
lockT2.signal();
lockT1.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
},"T1");
Thread t2 = new Thread(() -> {
lock.lock();
try {
for (int i = 1; i <= 26; i++) {
System.out.print(i);
lockT1.signal();
if (i<26){
lockT2.await();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
},"T2");
t1.start();
t2.start();
}
}