如何在java中实现线程
在Java中,可以通过以下两种方式来实现线程:
public class MyThread extends Thread {
@Override
public void run() {
// 线程履行的代码
System.out.println("线程运行中");
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start(); // 启动线程
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程履行的代码
System.out.println("线程运行中");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
不管是继承Thread类或实现Runnable接口,都需要重写run()
方法,该方法中定义线程要履行的代码。然后通过创建线程对象,并调用start()
方法来启动线程。
TOP