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

创建多个线程

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 @ 2022-03-03 23:01  一品堂.技术学习笔记  阅读(57)  评论(0编辑  收藏  举报