/**PageBeginHtml Block Begin **/ /***自定义返回顶部小火箭***/ /*生成博客目录的JS 开始*/ /*生成博客目录的JS 结束*/

创建多个线程

* 博客文章部分截图及内容来自于学习的书本及相应培训课程以及网络其他博客,仅做学习讨论之用,不做商业用途。
* 如有侵权,马上联系我,我立马删除对应链接。
* @author Alan
* @Email no008@foxmail.com

复制代码
package com.alanliu.Java8BasicCodeStuding.Java8BasciCode.Unit11_Thread.CreateMoreThreadImplementsRunnable;

/**
 * 
 * @ClassName: NewThread
 * @Description: 创建多个线程
 * 
 * * 多线程 实现:
 * 
 * 1:基于主线程获取对其的引用。 Thread t = Thread.currentThread();
 * 2:implements 实现 Runnable 接口 
 * 3:extends 继承 Thread 类的方法。
 * 
 * Thread类的方法:
 * getName()   获取线程的名称
 * getPriority() 获取线程的优先级
 * isAlive()  确定线程是否仍然在运行
 * join()  等待线程终止
 * run()  线程的入口点
 * sleep() 挂起线程一段时间
 * start()  通过调用线程的run()方法启动线程。
 * 、
 * 
 * @author: Alan_liu
 * @date: 2022年3月3日 下午10:51:42
 * @Copyright:
 */
// Create multiple threads.
class NewThread implements Runnable {
    String name; // name of thread
    Thread t;

    NewThread(String threadname) {
        name = threadname;
        t = new Thread(this, name); //创建线程实例化。
        System.out.println("New thread: " + t);
        t.start(); // Start the thread
    }

    // This is the entry point for thread.
    public void run() {
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println(name + ": " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println(name + "Interrupted");
        }
        System.out.println(name + " exiting.");
    }
}




package com.alanliu.Java8BasicCodeStuding.Java8BasciCode.Unit11_Thread.CreateMoreThreadImplementsRunnable;

/**
 * 
 * @ClassName:  MultiThreadDemo   
 * @Description: 创建多个线程
 *  
 * @author: Alan_liu
 * @date:   2022年3月3日 下午10:53:01      
 * @Copyright:
 */
class MultiThreadDemo {
    public static void main(String args[]) {
        /**
         * 示例:程序创建所需要的任意多个线程。
         * 
         * 初始化线程。
         */
        new NewThread("One"); // start threads
        new NewThread("Two");
        new NewThread("Three");

        try {
            // wait for other threads to end
            Thread.sleep(10000);  //确保子线程结束后才结束主线程。
        } catch (InterruptedException e) {
            System.out.println("Main thread Interrupted");
        }

        System.out.println("Main thread exiting.");
    }
}
复制代码

 

posted @   一品堂.技术学习笔记  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2021-03-03 confluence 6.12的安装
点击右上角即可分享
微信分享提示