书上说,执行一次性的线程,可以使用匿名的 Runnable 实例,但是,不知何时使用一次性的线程呢?
public class CreateDemo2New
{
public static final int MAX_TURN = 5;
static int threadNo = 1;
public static void main(String[] args)
{
Thread thread = null;
// 使用 Runnable 的匿名类创建和启动线程
for (int i = 0; i < 2; i ++) {
thread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < MAX_TURN; j ++) {
System.out.println(Thread.currentThread().getName() + ", 轮次:" + j);
}
System.out.println(Thread.currentThread().getName() + " 运行结束.");
}
}, "RunnabledThread" + threadNo ++);
thread.start();
}
System.out.println(Thread.currentThread().getName() + " 运行结束.");
}
}
使用匿名Runnable创建一次性线程的示例

该博客展示了如何在Java中通过匿名Runnable类创建和启动一次性的线程。代码示例创建了两个线程,每个线程运行指定次数并打印其运行状态。这种技术常用于执行独立的任务或简单的并发操作。

1230

被折叠的 条评论
为什么被折叠?



