继承Thread类实现多线程
package com.example.demo1;// 方式一:继承Thread类
class MyThread extends Thread {// 重写run()方法(线程执行体)@Overridepublic void run() {// 获取当前线程名称(通过父类方法)System.out.println("当前线程名(继承Thread): " + getName()); // 线程休眠示例(暂停200ms)try {Thread.sleep(200); } catch (InterruptedException e) {e.printStackTrace();}// 输出线程优先级System.out.println(getName() + " 优先级: " + getPriority()); }
}public class ThreadDemo {public static void main(String[] args) {// 创建线程对象MyThread t1 = new MyThread();MyThread t2 = new MyThread();// 设置线程名称(方式1:通过setName)t1.setName("线程A");// 设置线程名称(方式2:通过构造方法,需在MyThread中添加带参构造)t2 = new MyThread() {{ setName("线程B"); }}; // 设置优先级(范围1-10,默认5)t1.setPriority(Thread.MAX_PRIORITY); // 10t2.setPriority(Thread.MIN_PRIORITY); // 1// 启动线程(JVM会调用run())t1.start(); t2.start(); // 主线程输出当前线程信息System.out.println("主线程名: " + Thread.currentThread().getName()); }
}
实现Runnable接口
package com.example.demo1;// 方式二:实现Runnable接口(推荐,避免单继承限制)
class MyRunnable implements Runnable {@Overridepublic void run() {// 通过Thread.currentThread()获取当前线程对象Thread current = Thread.currentThread();System.out.println("当前线程名(Runnable): " + current.getName());// 线程休眠示例(暂停300ms)try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}}
}public class RunnableDemo {public static void main(String[] args) {// 创建Runnable任务MyRunnable task = new MyRunnable();// 使用Thread(Runnable target)构造线程Thread t1 = new Thread(task);// 使用Thread(Runnable target, String name)构造带名称的线程Thread t2 = new Thread(task, "线程C"); t1.start();t2.start();}
}
实现Callable接口
package com.example.demo1;import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;// 方式三:实现Callable接口(可获取返回值)
class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception { // 可声明异常Thread.sleep(100); // 模拟耗时操作return Thread.currentThread().getName() + " 执行完成"; }
}public class CallableDemo {public static void main(String[] args) throws Exception {// 创建Callable任务MyCallable callable = new MyCallable();// 用FutureTask包装Callable(桥接Callable和Thread)FutureTask<String> futureTask = new FutureTask<>(callable);// 启动线程(FutureTask本身是Runnable)new Thread(futureTask, "线程D").start(); // 获取结果(阻塞直到完成)String result = futureTask.get(); System.out.println("Callable返回结果: " + result);}
}
守护线程示例
package com.example.demo1;class DaemonTask implements Runnable {@Overridepublic void run() {while (true) {System.out.println("守护线程运行中...");try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}}
}public class DaemonThreadDemo {public static void main(String[] args) throws InterruptedException {Thread daemonThread = new Thread(new DaemonTask());// 设置为守护线程(必须在start()前调用)daemonThread.setDaemon(true); daemonThread.start();// 主线程运行2秒后结束Thread.sleep(2000);System.out.println("主线程结束,JVM退出");}
}