public class HelloRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello from thread: " +
Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread(new HelloRunnable());
thread.start();
// 主线程也输出问候
System.out.println("Hello from main: " +
Thread.currentThread().getName());
}
}
// 错误用法 - 这不会创建新线程 Runnable task = new MyRunnable(); task.run(); // 只是在主线程中执行
// 正确用法 Thread thread = new Thread(task); thread.start(); // 创建新线程并执行run()
你可能想看: