Thread 类的基本用法

发布于:2025-08-05 ⋅ 阅读:(17) ⋅ 点赞:(0)

线程创建

优先选择 lambda 表达式

Thread thread = new Thread(() -> {});

线程中断

thread.interrupt();
public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                //Thread.currentThread(); -> 获取当前线程引用
                System.out.println("Hello Thread");
                try {
                    Thread.sleep(10000);
                    //若阻塞时间过长,即便输入0后也不会立即终止。
                    //必须得等阻塞完之后才会终止执行
                } catch (InterruptedException e) {
                    // throw new RuntimeException(e);
                    // e.printStackTrace();//不会停止进程  sleep 会清除标志位
                    break;
                }
            }
        });
        thread.start();
        Scanner scanner = new Scanner(System.in);
        System.out.println("按零退出线程");
        int input = scanner.nextInt();
        if (input == 0) {
            thread.interrupt();
        }
    }

线程等待

thread.join();

 

public class Demo10 {
    private static int ret = 0;
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i = 1; i <= 1000; i++) {
                ret += i;
            }
        });
        thread.start();
        System.out.println(ret);
    }
}

此时输出的结果就为 0。因为 thread 线程和 main 线程同时进行导致 main 线程在读取 ret 的值时仍旧为 0 。

解决方法:只需在线程 thread start 之后调用 thread 的 join 方法,此时 main 线程就会排在 thread 线程之后。此时的输出结果即为正常结果。

public class Demo10 {
    private static int ret = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 1; i <= 1000; i++) {
                ret += i;
            }
        });
        thread.start();
        thread.join();
        System.out.println(ret);
    }
}

线程休眠

Thread.sleep(1000);

 

获取线程实例

    public static void main(String[] args) {
        Thread t1 = new Thread() {
            public void run() {
                //可通过this.getName()获取当前线程名
                System.out.println(this.getName());
            }
        };
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                //System.out.println(this.getName());
                //报错,此时的 this 指代的是 Runnable, 而 Runnable 内没有 getName() 方法

                //仍需调用用Thread类中的Thread.currentThread()获取当前线程
                Thread cur = Thread.currentThread();
                System.out.println(cur.getName());
                System.out.println(Thread.currentThread().getName());
            }
        });
        t2.start();

        Thread t3 = new Thread(() -> {
            //lambda 表达式也是如此,同t2,不支持this
            System.out.println(Thread.currentThread().getName());
        });
        t3.start();
    }


网站公告

今日签到

点亮在社区的每一天
去签到