> 文章列表 > 【Java】多线程

【Java】多线程

【Java】多线程

创建线程

Thread

创建自己的线程类,继承与 Thread 并重写 run() 方法

class MyThread extends Thread {@Overridepublic void run() {while (true) {System.out.println("线程运行中");}}
}

创建 MyThread 的实例(new 一个 MyThread 对象)

MyThread myThread = new MyThread();

调用 myThread 对象中的 start() 方法,开启线程

myThread.start();

Runnerable

 创建自己的 Runnable 类,实现 Runnable 接口并重写 run() 方法

class MyRunnable implements Runnable {@Overridepublic void run() {while (true) {System.out.println("线程运行中");}}
}

使用 Thread 的 Thread(Runnable runnable) 构造方法构造 Thread 实例

MyThread myThread = new MyThread(new MyRunnable);

调用 myThread 对象中的 start() 方法,开启线程

myThread.start();

匿名内部类

Thread thread = new Thread(@Overrridepublic void run() {while (true) {System.out.println("线程运行中");}}
);
Thread thread = new Thread(new Runnable (@Overrridepublic void run() {while (true) {System.out.println("线程运行中");}})
);

lambda

Thread thread = new Thread(() -> System.out.println("线程启动"));
Thread thread = new Thread(() -> {while (true) {System.out.println("线程运行中");}
});

Thread 与 Runnable

Thread 为类,Runnable 为接口

当一个继承与父类的子类需要作为线程运行时,无法在继续继承一个 Thread,只能通过 Runnable 接口去实现线程功能

两者获取当前线程引用的方式也不同

使用继承 Thread 的方式创建的线程在 run() 方法中可以直接使用 this 来获取当前线程实例

使用 Thread(Runnable runnable) 方式创建的线程,run() 方法是属于 runnable 实现类的因此无法使用 this 来获取当前线程,只能使用 Thread 类中的 currentThread() 静态方法来获取当前线程实例

电动牙刷