用java两个线程输出1-100
时间: 2023-03-24 09:03:04 浏览: 139
java10个线程按照顺序打印1-100
我可以回答这个问题。可以使用两个线程分别输出1-50和51-100的数字。具体实现可以使用synchronized关键字来保证线程安全。以下是示例代码:
```
public class PrintThread implements Runnable {
private int start;
private int end;
private Object lock;
public PrintThread(int start, int end, Object lock) {
this.start = start;
this.end = end;
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
lock.notifyAll();
try {
if (i != end) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main {
public static void main(String[] args) {
Object lock = new Object();
PrintThread thread1 = new PrintThread(1, 50, lock);
PrintThread thread2 = new PrintThread(51, 100, lock);
new Thread(thread1, "Thread-1").start();
new Thread(thread2, "Thread-2").start();
}
}
```
阅读全文