线程|三个线程 依次打印 数字1~50

主要思想:
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
文章图片

*****
线程|三个线程 依次打印 数字1~50
文章图片

【线程|三个线程 依次打印 数字1~50】结论:
实现多线程的依次输出,主要就是判断当前线程是否轮到它进行输出,不是则等待,是就进行输出即可。还有一些细节方面代码优化,线程的关闭等。自己写的不是很到位,希望大家多多批评指正。

    推荐阅读