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.");
}
}
为人:谦逊、激情、博学、审问、慎思、明辨、 笃行
学问:纸上得来终觉浅,绝知此事要躬行
为事:工欲善其事,必先利其器。
态度:道阻且长,行则将至;行而不辍,未来可期
转载请标注出处!