Thread类的基本用法

发布于:2024-10-17 ⋅ 阅读:(11) ⋅ 点赞:(0)

1.创建线程

方法1:继承Thread类

public class Demo1 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        while (true) {
            System.out.println("main");
        }
    }

}

class MyThread extends Thread {
    public void run() {
        while (true) {
            System.out.println("MyThread");
        }
    }
}

方法2.使用匿名内部类

    public static void main(String[] args) {
        Thread thread = new Thread() {
            public void run() {
                while (true) {
                      System.out.println("Thread");                      
              }
          }
        };
        thread.start();

        while (true) {
            System.out.println("main");
        }
    }

 方法3.使用lambda表达式

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("Thread");
            }
        });
        thread.start();

        while (true) {
            System.out.println("mian");
        }
    }

注意,在使用lambda表达式时,若要使用外面的变量(main中的局部变量但不在lambda中的变量),则该变量不能被修改,因为使用时会触发变量捕获,由于lambda是回调函数,执行时机是很久之后(操作系统真正创建出线程后才会执行),有可能main先执行完,导致该变量在使用前就被销毁,于是该变量不能被修改。

若该变量为引用类型,则这个引用一旦指向一个对象后,就不能指向其他对象,但指向的对象本体的属性和方法能被修改。

在上述代码中,都使用了Thread来创建线程thread,再使用start()方法来启动线程,虽然thread.run()也能使程序运行,但本质上并没有创建出一个新的线程,只是普通的方法调用。

2.线程中断(终止)

使用thread.interrupt()方法可使thread线程终止运行,但该方法还会唤醒阻塞方法(如sleep),唤醒后可能会报错。

也可以直接在run方法中直接return,从而使该线程终止运行。

isInterruptrd()可以判断线程是否终止,若终止返回true。

3.线程休眠

使用sleep()方法可使当前线程自动放弃CPU资源从而使该线程停止运行,休眠时间为毫秒,使用该方法时要处理异常。

4.获取线程实例

当我们使用匿名内部类和lambda表达式时,由于thread线程还未创建,这这时要在run()方法中使用该线程的实例时,就要调用Thread.currentThread()方法来获取该线程的引用,该方法为静态方法。