在 Java 中实现多线程的数字计数器可以使用 Thread 类和 Runnable 接口。
首先,需要定义一个全局变量来存储所有线程计数的总和。然后,对于每个需要计数的数字,创建一个新的线程,在线程中实现计数逻辑。最后,在主线程中输出计数总和。
下面是一个示例代码:
public class Main {
static int count = 0;
public static void main(String[] args) {
Thread t1 = new Thread(new CountThread(1));
Thread t2 = new Thread(new CountThread(2));
Thread t3 = new Thread(new CountThread(3));
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Total count: " + count);
}
}
class CountThread implements Runnable {
int number;
CountThread(int number) {
this.number = number;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (Main.class) {
Main.count += number;
}
}
}
}
这段代码中, 一共有三个线程 t1,t2,t3 分别计数 1,2,3,并且计数结束后将结果累加到全局变量count中,最后在主线程中输出计数总和。
注意:在更新全局变量 count 时,需要使用同步机制(如 synchronized 关键字)来保证线程安全。