Java 多线程详解:用法、继承与接口示例
Java 中多线程的用法主要包含以下步骤:
-
定义一个类:您可以通过以下两种方式创建线程:
- 继承 Thread 类:定义一个类继承
Thread类,并重写run()方法,在该方法中定义线程要执行的任务。 - 实现 Runnable 接口:定义一个类实现
Runnable接口,并重写run()方法,在该方法中定义线程要执行的任务。
- 继承 Thread 类:定义一个类继承
-
重写 run() 方法:
run()方法是线程执行的入口,您需要在该方法中定义线程需要执行的任务。 -
创建线程对象:使用您定义的类创建线程对象。
-
调用 start() 方法启动线程:调用
start()方法启动线程,线程会自动执行run()方法中的任务。 -
线程执行完任务后自动结束:线程执行完
run()方法中的任务后,会自动结束。
示例代码:
继承 Thread 类的方式:
public class MyThread extends Thread {
@Override
public void run() {
// 线程要执行的任务
System.out.println('线程执行了任务');
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现 Runnable 接口的方式:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程要执行的任务
System.out.println('线程执行了任务');
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
通过以上步骤和示例代码,您可以轻松地创建和使用 Java 多线程,提高程序的效率和响应速度。
原文地址: https://www.cveoy.top/t/topic/ngPe 著作权归作者所有。请勿转载和采集!