多线程编程是Java开发的核心技术之一,掌握线程创建方式对提升程序性能至关重要。本文将详细介绍五种常见实现方法。
sleep方法使线程暂时进入阻塞状态,暂停执行指定时长class MyThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class Demo3 {
public static void main(String[] args) throws InterruptedException {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
while (true) {
System.out.println("hello main");
Thread.sleep(1000);
}
}
}
Runnable需要配合Thread作为执行载体run方法,直接实现接口即可Runnable中定义的run逻辑public class Demo3 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
@Override
public void run() {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
t.start();
while (true) {
System.out.println("hello main");
Thread.sleep(1000);
}
}
}

Threadrun方法定义线程逻辑start启动线程该方法适合一次性使用场景。
public class Demo3 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
t.start();
while (true) {
System.out.println("hello main");
Thread.sleep(1000);
}
}
}
Runnable接口Thread构造器public class Demo5 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
t.start();
while (true) {
System.out.println("hello main");
Thread.sleep(1000);
}
}
}
Runnablepublic static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("hello");
});
thread.start();
thread.start(); // 报错!
thread.start();
}
IllegalThreadStateException异常Thread对象与系统线程一一对应Thread实例仅允许start一次Runnable接口,任务与执行载体解耦import语句引入所需类java.lang包默认自动导入本文全面解析了Java线程的五种创建方式,从基础实现到高级语法,帮助开发者掌握多线程编程的核心技术。