多线程交替打印
有三个线程,1号线程打印数字1,2号线程打印数字2,3号线程打印数字3,要求:
1、三个线程交替打印
2、1号线程打印100次,2号线程打印200次,3号线程打印300次
package com.example.springbootdemo2;
/**
* @author evanYang
* @since 2024/2/1 8:05 PM
*/
public class Test {
private static final Object lock = new Object();
private static int currentThread = 1;
private static int printedCount = 0;
public static void main(String[] args) {
//Scanner in = new Scanner(System.in);
//int a = in.nextInt();
//System.out.println(a);
System.out.println("Hello World!");
Thread t1 = new Thread(new PrintDemo(1, 100));
Thread t2 = new Thread(new PrintDemo(2, 200));
Thread t3 = new Thread(new PrintDemo(3, 300));
t1.start();
t2.start();
t3.start();
}
static class PrintDemo implements Runnable{
private int threadId;
private int printCount;
public PrintDemo(int threadId,int printCount){
this.threadId = threadId;
this.printCount = printCount;
}
@Override
public void run() {
for (int i = 0; i < printCount; i++) {
synchronized (lock) {
while(currentThread != threadId){
try {
lock.wait();
} catch (Exception e) {
System.out.println("eeeee_____---");
e.printStackTrace();
}
}
if (printedCount > printCount) {
break;
}
System.out.println("thread " + threadId + ":" + String.valueOf(printedCount+1));
if(threadId == 1) {
currentThread = 2;
}else if(threadId == 2) {
currentThread =3;
}else if(threadId == 3) {
currentThread =1;
}
lock.notifyAll();
}
}
}
}
}