需求:两个线程实现1-26,26个数字和A-Z,26个字母进行交替打印,字母开头,数字结尾。
方式一:通过LockSupport实现
public class AlternatePrint {
static Thread t1, t2;
static Integer[] nums = new Integer[26];
static char[] chars = new char[26];
//生成测试数据A~Z,1~26
static {
for (int i = 0; i < 26; i++) {
chars[i] = (char) ('A' + (i));
nums[i] = i + 1;
}
}
public static void main(String[] args) {
t1 = new Thread(() -> {
for (char c : chars) {
System.out.print(c);//输出字符
LockSupport.unpark(t2);//恢复线程t2
LockSupport.park();//暂停当前线程
}
}, "t1");
t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int n : nums) {
LockSupport.park();//暂停当前线程
System.out.print(n);
LockSupport.unpark(t1);//恢复线程t1
}
}
});
//启动线程
t1.start();
t2.start();
}
}
方式二:wait(),notify()实现
public class AlternatePrint2 {
static Integer[] nums = new Integer[26];
static char[] chars = new char[26];
static Object lock = new Object();//生成锁
private static CountDownLatch countDownLatch = new CountDownLatch(1);//门闩保证字符线程先打印
//生成测试数据A~Z,1~26
static {
for (int i = 0; i < 26; i++) {
chars[i] = (char) ('A' + (i));
nums[i] = i + 1;
}
}
public static void main(String[] args) {
new Thread(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
for (int n : nums) {
System.out.print(n);
lock.notify();//恢复线程t1
try {
lock.wait();//暂停当前线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notifyAll();//必须写否则无法停止程序
}
}, "t2").start();
new Thread(() -> {
synchronized (lock) {
for (char c : chars) {
System.out.print(c);//输出字符
countDownLatch.countDown();
lock.notify();//恢复线程t2
try {
lock.wait();//暂停当前线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notifyAll();//必须写否则无法停止程序
}
}, "t1").start();
}
}