...线程,第一个线程输入1-50之间的值,第二个线程输出51-100之间的值...
发布网友
发布时间:2024-04-10 06:05
我来回答
共1个回答
热心网友
时间:2024-04-14 14:50
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
Test test = new Test();
Thread task1 = new Thread(test.new Task(1, 50), "线程1");
Thread task2 = new Thread(test.new Task(51, 100), "线程2");
Thread task3 = new Thread(test.new Task(101, 150), "线程3");
task1.setPriority(8);
task2.setPriority(5);
task3.setPriority(3);
task1.start();
task2.start();
task3.start();
}
class Task implements Runnable {
public static final String lock = "lock";
private int startNum;
private int endNum;
public Task(int startNum, int endNum) {
this.startNum = startNum;
this.endNum = endNum;
}
@Override
public void run() {
for (int i = startNum; i <= endNum; i++) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "打印" + i);
}
}
}
}
}