在Java中,可以通过继承Thread类或实现Runnable接口来创建线程。以下是Thread类常用方法的使用示例:
Thread thread = new MyThread(); // MyThread是自定义的继承Thread类的线程类
thread.start(); // 启动线程
public class MyThread extends Thread {
@Override
public void run() {
// 线程的具体执行逻辑
System.out.println("线程开始执行");
}
}
Thread thread = new MyThread();
thread.start(); // 输出 "线程开始执行"
Thread thread = new MyThread();
thread.start();
try {
Thread.sleep(1000); // 休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread thread = new MyThread();
thread.start();
try {
thread.join(); // 等待线程终止
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread thread = new MyThread();
thread.start();
boolean isAlive = thread.isAlive(); // 判断线程是否还活着
注意:以上示例中的MyThread是自定义的继承Thread类的线程类,也可以使用实现Runnable接口的方式创建线程,然后将Runnable对象传递给Thread类的构造方法来创建线程。