java线程:每隔一秒输出一个数据

java线程:每隔一秒输出一个数据
2025-03-23 02:45:33
推荐回答(3个)
回答1:

public static void main(String[] args) {
new Thread(new Runnable() {

@Override
public void run() {
while (true) {
System.out.println("数据");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}

回答2:


回答3:

public static void main(String[] args) {
BlockingQueue queue = new LinkedBlockingQueue();
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 1, TimeUnit.DAYS, queue);

for (int i = 0; i < 20; i++) {
executor.execute(new Runnable() {

public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("thread %d finished", this.hashCode()));
}
});
}
executor.shutdown();
}