多线程基础-常用方法

2024/06/20 Java

Thread常用方法介绍

  1. currentThread() 获取到当前线程的对象实例

Thread类

public static native Thread currentThread();

Thread thread = Thread.currentThread();
  1. getName() 获取当前线程的名称

Thread类

public final String getName() { return name; }

可以直接在它的子类中调用;

public class MyThread extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(getName() + "执行了" + i + "次");
        }
    }
}
// MyThread中没有getName(),会调用调用父类的getName方法

而在主线程中,MyThread_Main没有继承Thread类,所以只能通过获取当前线程的实例来调用

public class MyThread_Main {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "主线程执行了" + i + "次");
        }
    }
}
// 这是一个链式调用,Thread.currentThread()返回了一个Thread实例,再掉用其getName()方法
  1. setName(String name) 既然有getName那对应的,肯定有setName()

  2. sleep(long millis) 休眠

Thread类

public static native void sleep(long millis) throws InterruptedException;

我们可以用该方法延长每一次线程执行的时间,让错误暴露出来

public class MyThread extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(getName() + "执行了" + i + "次");
        }
    }
}

public class MyThread_Main {

    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        myThread.start();

        for (int i = 0; i < 10; i++) {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "主线程执行了" + i + "次");
        }
    }
}

可以看到我们在自定义MyThread类中,只能try-catch,而不能抛出异常; 这是因为我们重写父类的run方法,而父类的run方法是没有抛出异常的

  1. setPriority() 设置优先级

Thread类

  public final void setPriority(int newPriority) {
        ThreadGroup g;
        checkAccess();
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
            throw new IllegalArgumentException();
        }
        if((g = getThreadGroup()) != null) {
            if (newPriority > g.getMaxPriority()) {
                newPriority = g.getMaxPriority();
            }
            setPriority0(priority = newPriority);
        }
    }

MAX_PRIORITY - 10 | MIN_PRIORITY - 1

优先级最大值为10,最小值为1,超出范围会抛出错误 设置优先级并不是能保证执行顺序,只是优先度会更高

  1. getPriority() 设置优先级

  2. setDaemon(true); 设置为守护线程

当其他线程执行完毕,该线程会停止执行(不是立刻停止执行)

应用场景:比如说聊天的时候下载文件,当聊天窗口关闭,文件下载自动停止

  1. yield() 礼让线程,放开CPU占用,重新进行抢占

public static native void yield();

下一次执行的可能仍然是礼让的线程

  1. join() 将线程插到当前线程之前(在main中即主线程)

Search

    Table of Contents