按顺序运行 Java 线程 [英] Run Java Threads sequentially

查看:33
本文介绍了按顺序运行 Java 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你将如何顺序执行三个线程?例如.线程 1、线程 2、线程 3.不可能将一个线程的引用传递给另一个并从 run() 方法调用.

How will you execute Three threads sequentially? For eg. Thread1, Thread2, Thread3. It is not possible to pass the reference of one Thread to the other and invoke from the run() method.

所以代码应该是这样的:

So code should be like this:

 Thread1.start();
 Thread2.start();
 Thread3.start();

输出应该是

 Printing Thread1
 Printing Thread2
 Printing Thread3

这可以通过使用 ThreadPoolExecutor 和使用阻塞队列来实现,但即使这样也不是可接受的答案.

This can be possible by using ThreadPoolExecutor and using a blocking queue but even that is not an acceptable answer.

推荐答案

使用 ExecutorService 在 java.util.concurrent 包中.更准确地使用 Executors.newSingleThreadExecutor();

Use ExecutorService in java.util.concurrent package. More precisely use Executors.newSingleThreadExecutor();

这篇关于按顺序运行 Java 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆