多个线程打印不重复的打印一到一百的java代码
时间: 2023-09-02 21:12:28 浏览: 48
以下是一个使用Java多线程实现不重复打印1到100的示例代码:
```
public class PrintNumber {
private static volatile int num = 1;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while (num <= 100) {
synchronized (PrintNumber.class) {
if ((num % 3 == 0 && Thread.currentThread().getName().equals("Thread-0")) ||
(num % 3 == 1 && Thread.currentThread().getName().equals("Thread-1")) ||
(num % 3 == 2 && Thread.currentThread().getName().equals("Thread-2"))) {
System.out.println(Thread.currentThread().getName() + ": " + num);
num++;
}
}
}
}
};
Thread t1 = new Thread(runnable, "Thread-0");
Thread t2 = new Thread(runnable, "Thread-1");
Thread t3 = new Thread(runnable, "Thread-2");
t1.start();
t2.start();
t3.start();
}
}
```
这个程序中,我们使用了一个volatile变量num来表示当前需要打印的数。每个线程通过synchronized关键字来获取PrintNumber类的锁,通过判断num的值和当前线程的名称来确定是否打印。其中,num%3的结果用来确保三个线程打印的数字不重复。