马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
二面被问到的手撕题,自己总计一下。考察的还是比较基础的,但也是对自己知识领悟程度的考察。
写一个程序,要求创建三个线程依次打印hello+线程号。
考察多线程和同步的知识点应用
这里设置为打印10轮。
- package 多线程;
- /**
- * @Author wuyifan
- * @Date 2024/6/4 20:11
- * @Version 1.0
- */
- class PrintSequence implements Runnable {
- private int threadId;
- private static final Object lock = new Object();
- private static int currentThreadId = 0;
- private int printCount = 10;
- public PrintSequence(int threadId) {
- this.threadId = threadId;
- }
- @Override
- public void run() {
- for (int i = 0; i < printCount; ) {
- synchronized (lock) {
- if (currentThreadId % 3 == threadId) {
- System.out.println("Thread " + threadId + ": hello" + (i + 1));
- i++;
- currentThreadId++;
- lock.notifyAll(); // 唤醒所有等待的线程
- } else {
- try {
- lock.wait(); // 等待其他线程的唤醒
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
- public class New3Thread {
- public static void main(String[] args) {
- Thread t1 = new Thread(new PrintSequence(0), "T1");
- Thread t2 = new Thread(new PrintSequence(1), "T2");
- Thread t3 = new Thread(new PrintSequence(2), "T3");
- t1.start();
- t2.start();
- t3.start();
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |