多线程面试题-线程通信
作者:互联网
- 线程间通信:两个线程交替打印
- 第一个线程打印1-26,第二个线程打印A-Z
- 即最终结果为:1A2B3C…26Z
package com.example.mca.thread;
import java.util.concurrent.locks.LockSupport;
/**
* 线程间通信:两个线程交替打印
* 第一个线程打印1-26,第二个线程打印A-Z
* 即最终结果为:1A2B3C......26Z
*/
public class ThreadCommunication {
static Thread t1 = null;
static Thread t2 = null;
public static void main(String[] args) {
t1 = new Thread(() -> {
for (int i = 0; i < 26; i++) {
System.out.print(i + 1);
LockSupport.unpark(t2);
LockSupport.park(t1);
}
System.out.println("\n~~~~~~~ t1 execute over ~~~~~~~");
LockSupport.unpark(t2);
});
t2 = new Thread(() -> {
for (int i = 0; i < 26; i++) {
if (i == 0) {
LockSupport.park(t2);
}
System.out.print((char) (65 + i) + " ");//A对应的ASCII码为65
LockSupport.unpark(t1);
LockSupport.park(t2);
}
System.out.println("~~~~~~~ t2 execute over ~~~~~~~");
LockSupport.unpark(t1);
});
t1.start();
t2.start();
}
}
标签:System,面试题,打印,t2,LockSupport,t1,线程,多线程 来源: https://blog.csdn.net/qq_17611883/article/details/115682012