创建线程有两种常见的“套路”:继承Thread类和实现Runnable接口。就像不同的开车方法,它们最终目的都一样——让我们的程序能“并行”工作,但适用场景略有不同。
这是创建线程的最简单方式,直接让你的类继承Thread,然后重写run()
方法,把你想让线程干的活写在run()
里。接下来,创建对象并调用start()
方法,线程就启动啦!
class MyThread extends Thread {
@Override
public void run() {
System.out.println("继承Thread类的线程正在运行!");
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
run()
方法里,一目了然。实现Runnable接口更加灵活——你不用继承任何类,只需实现Runnable接口,然后在run()
方法里写线程要干的事。创建线程时将Runnable对象传给Thread的构造器,然后调用start()
启动线程。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口的线程正在运行!");
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 启动线程
}
}
无论选择哪个方法,最终都能让程序多线程并行工作,灵活运用这两种方法,让代码更高效!
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- huatuo8.com 版权所有 湘ICP备2023022238号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务