java多线程计数并输出
时间: 2023-07-19 09:40:57 浏览: 47
好的,以下是一个简单的Java多线程计数并输出的示例代码:
```java
public class Counter implements Runnable {
private static int count = 0;
private int id;
public Counter(int id) {
this.id = id;
}
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (Counter.class) {
count++;
System.out.println("Thread " + id + " count is " + count);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Counter(1));
Thread t2 = new Thread(new Counter(2));
t1.start();
t2.start();
}
}
```
在这个例子中,我们创建了一个名为Counter的类,并实现了Runnable接口,使得该类可以作为线程的任务来运行。在每个线程的run方法中,我们使用synchronized关键字来确保count变量的安全访问,避免多个线程同时修改count而导致计数错误。每个线程都会循环计数10次,并输出当前的计数值。在main方法中,我们创建了两个线程,并启动它们来执行任务。最终的输出结果应该是交替出现的两个线程的计数值。