▌多线程是什么
运行一个程序叫做一个线程,运行过程中时处理多个任务,这些任务叫做线程(比如同时播放画面和声音)
注:真正的多线程需要多核CPU同时处理多个线程,单核的是伪多线程(单核同一时间只能处理一个线程,但是线程之间切换很多,毫秒级,所以看起来像是在同时处理)
▌一、继承类Thread
-
创建一个类
TestThread
-
继承父类
Thread
-
重写方法
Run
-
new对象
TestThread
-
开启多个线程
对象名.start()
public class TestThread extends Thread {
<@Override public void run(){ //输出当前线程的名字 System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { //创建三个线程 TestThread t1 = new TestThread(); TestThread t2 = new TestThread(); TestThread t3 = new TestThread(); //线程开始 t1.start(); t2.start(); t3.start(); }