18.3.1 线程创建方式与生命周期管理

1. 线程创建方式概述

1.1 Java中创建线程的四种主要方式

public class ThreadCreationMethods {
    
    // 方式1: 继承Thread类
    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("继承Thread类创建线程: " + Thread.currentThread().getName());
        }
    }
    
    // 方式2: 实现Runnable接口
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("实现Runnable接口创建线程: " + Thread.currentThread().getName());
        }
    }
    
    // 方式3: 实现Callable接口
    static class MyCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("实现Callable接口创建线程: " + Thread.currentThread().getName());
            return "Callable返回结果";
        }
    }
    
    public void demonstrateThreadCreation() {
        // 1. 继承Thread类
        MyThread thread1 = new MyThread();
        thread1.start();
        
        // 2. 实现Runnable接口
        Thread thread2 = new Thread(new MyRunnable());
        thread2.start();
        
        // 3. 使用Lambda表达式
        Thread thread3 = new Thread(() -> {
            System.out.println("Lambda表达式创建线程: " + Thread.currentThread().getName());
        });
        thread3.start();
        
        // 4. 实现Callable接口
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new MyCallable());
        
        try {
            String result = future.get();
            System.out.println("Callable结果: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}

1.2 线程创建方式对比分析

继承Thread

简单直接

无法继承其他类,资源开销大

简单的线程任务

实现Runnable

可继承其他类,资源共享

无返回值

一般的异步任务

实现Callable

有返回值,可抛异常

需要配合ExecutorService

需要返回结果的任务

线程池

资源复用,便于管理

配置复杂

生产环境推荐

2. 线程生命周期详解

2.1 线程状态转换

public class ThreadLifecycleDemo {
    
    public void demonstrateThreadStates() {
        // 创建线程对象
        Thread thread = new Thread(() -> {
            try {
                System.out.println("线程开始执行");
                
                // RUNNABLE状态
                for (int i = 0; i < 3; i++) {
                    System.out.println("执行中: " + i);
                    Thread.sleep(1000); // TIMED_WAITING状态
                }
                
                // 同步块演示BLOCKED状态
                synchronized (ThreadLifecycleDemo.class) {
                    System.out.println("获得锁,继续执行");
                    Thread.sleep(1000);
                }
                
                System.out.println("线程执行完毕");
            } catch (InterruptedException e) {
                System.out.println("线程被中断");
                Thread.currentThread().interrupt();
            }
        });
        
        // NEW状态
        System.out.println("创建后状态: " + thread.getState());
        
        // 启动线程,进入RUNNABLE状态
        thread.start();
        System.out.println("启动后状态: " + thread.getState());
        
        // 监控线程状态变化
        new Thread(() -> {
            while (thread.isAlive()) {
                System.out.println("当前状态: " + thread.getState());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
            System.out.println("最终状态: " + thread.getState());
        }).start();
    }
}

2.2 线程状态详细说明

public class ThreadStateAnalysis {
    
    // 演示BLOCKED状态
    public void demonstrateBlockedState() {
        Object lock = new Object();
        
        // 第一个线程获取锁
        Thread thread1 = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("线程1获得锁");
                    Thread.sleep(3000); // 持有锁3秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        
        // 第二个线程等待锁
        Thread thread2 = new Thread(() -> {
            synchronized (lock) {
                System.out.println("线程2获得锁");
            }
        });
        
        thread1.start();
        try {
            Thread.sleep(100); // 确保thread1先获得锁
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        thread2.start();
        
        try {
            Thread.sleep(500); // 等待thread2进入BLOCKED状态
            System.out.println("线程2状态: " + thread2.getState()); // BLOCKED
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    // 演示WAITING状态
    public void demonstrateWaitingState() {
        Object lock = new Object();
        
        Thread waitingThread = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("线程进入等待状态");
                    lock.wait(); // 进入WAITING状态
                    System.out.println("线程被唤醒");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        
        Thread notifyThread = new Thread(() -> {
            try {
                Thread.sleep(2000); // 等待2秒
                synchronized (lock) {
                    System.out.println("唤醒等待线程");
                    lock.notify();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        
        waitingThread.start();
        notifyThread.start();
        
        try {
            Thread.sleep(1000);
            System.out.println("等待线程状态: " + waitingThread.getState()); // WAITING
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    // 演示TIMED_WAITING状态
    public void demonstrateTimedWaitingState() {
        Thread thread = new Thread(() -> {
            try {
                System.out.println("线程开始休眠");
                Thread.sleep(3000); // 进入TIMED_WAITING状态
                System.out.println("线程休眠结束");
            } catch (InterruptedException e) {
                System.out.println("线程被中断");
                Thread.currentThread().interrupt();
            }
        });
        
        thread.start();
        
        try {
            Thread.sleep(500);
            System.out.println("休眠线程状态: " + thread.getState()); // TIMED_WAITING
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

3. 线程生命周期管理

3.1 线程启动与停止

public class ThreadL

剩余60%内容,订阅专栏后可继续查看/也可单篇购买

Java面试圣经 文章被收录于专栏

Java面试圣经,带你练透java圣经

全部评论

相关推荐

09-22 22:22
中山大学 Java
乌鱼子萨奇:羡慕你啊,直接转正了,都不用经历秋招的炼狱,但是你少经历了很多痛苦的事情啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务