主要思想:
1,实现Runnable接口,重写run()方法
2,每个线程有唯一标识,这里取得是该下标
3,三个线程共享一个输出变量 threadNo
4,线程取一个公共的“见证对象”,就可以保证对线程进行一致的操作
5,判断是否轮到当前线程输出,是则输出,不是则等待
6,退出执行:到达输出上限50
参考代码:
import java.io.IOException;
/**
* 线程:实现Runnable接口的方式,三个线程依次实现 1~50 数字的输出
*
* @author Sanyi
*
* */
public class ThreadPrint implements Runnable { /**
* 公认的对象
* */
private static final Object LOCK = new Object();
/**
* 线程数
* */
private static final int THREAD_NUM = 3;
/**
* 输出最大的数字
* */
private static final int MAX_NUM = 50;
// 当前数字
private static int currentNo = 0;
// 线程编号
private int threadNo;
// 线程总数
private int threadCnt;
// 数字总数
private int max;
/**
* 无参构造
* */
public ThreadPrint() {
} /**
* 重写构造函数
* */
public ThreadPrint(int max, int threadNo, int threadCnt) {
this.max = max;
this.threadCnt = threadCnt;
this.threadNo = threadNo;
} /**
* 重写 run() 方法
* */
@Override
public void run() {
try {
// 默认一直执行
while (true) {
synchronized (LOCK) {
// 判断是否当前线程编号
while (currentNo % threadCnt != threadNo) {
// 不符合跳出
if (currentNo >= max) {
break;
}
try {
// 等待
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 不符合跳出
if (currentNo >= max) {
break;
}
// 打印当前线程和数字
System.out.println("线程 " + (threadNo + 1) + ":"
+ (currentNo + 1));
currentNo++;
LOCK.notifyAll();
}
}
} catch (Exception e) {
e.printStackTrace();
} } /**
* main 方法入口
* */
public static void main(String[] args) throws IOException {
// 起三个线程
for (int i = 0;
i < THREAD_NUM;
i++) {
new Thread(new ThreadPrint(MAX_NUM, i, THREAD_NUM)).start();
}
}
}
输出:
![线程|三个线程 依次打印 数字1~50](https://img.it610.com/image/info8/78c7e585be44487c8c748b93dd593f21.png)
文章图片
*****
![线程|三个线程 依次打印 数字1~50](https://img.it610.com/image/info8/be9ef47f9c6e4ce99661e5c729fca44b.png)
文章图片
【线程|三个线程 依次打印 数字1~50】结论:
实现多线程的依次输出,主要就是判断当前线程是否轮到它进行输出,不是则等待,是就进行输出即可。还有一些细节方面代码优化,线程的关闭等。自己写的不是很到位,希望大家多多批评指正。
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)