华为OD面试真题精选
专栏:华为OD面试真题精选
目录: 2024华为OD面试手撕代码真题目录以及八股文真题目录
线程创建的方式
1. 通过继承Thread类
创建一个自定义线程类,继承Java中的Thread
类,并重写run()
方法。然后通过调用start()
方法来启动线程。
示例代码:
// 继承Thread类
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
// 创建线程对象
MyThread thread = new MyThread();
// 启动线程
thread.start();
}
}
2. 通过实现Runnable接口
如果需要让多个类继承其他类,可以选择实现Runnable
接口。这种方式不会限制类的继承结构,可以同时继承其他类。
示例代码:
// 实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
// 创建Runnable对象
MyRunnable myRunnable = new MyRunnable();
// 创建Thread对象并传入Runnable对象
Thread thread = new Thread(myRunnable);
// 启动线程
thread.start();
}
}