线程(Thread 类)的常用方法

在 Java 中,线程(Thread 类)提供了许多常用方法,这些方法可以帮助你创建、控制和管理线程。以下是一些常见的线程方法及其使用示例:

1. 线程的创建与启动

  • Thread():无参构造方法,用于创建一个新的线程对象。
  • Thread(Runnable target):通过传入一个实现了 Runnable 接口的对象来创建线程。
  • start():启动线程,使线程进入就绪状态,等待 CPU 调度执行其 run() 方法。
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程正在执行,线程名:" + Thread.currentThread().getName());
    }
}

public class ThreadCreationExample {
    public static void main(String[] args) {
        // 使用 Runnable 接口创建线程
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

2. 线程的执行方法

  • run():线程的执行体,当线程被调度执行时,会调用该方法。通常需要重写此方法来定义线程要执行的任务。

3. 线程的控制方法

  • sleep(long millis):使当前线程暂停执行指定的毫秒数,进入阻塞状态。该方法是静态方法,会抛出 InterruptedException 异常。
public class ThreadSleepExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                System.out.println("线程开始睡眠");
                Thread.sleep(2000); // 线程睡眠 2 秒
                System.out.println("线程睡眠结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}

  • join():等待调用该方法的线程执行完毕后,当前线程才会继续执行。会抛出 InterruptedException 异常。
public class ThreadJoinExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                System.out.println("线程 1 执行:" + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                thread1.join(); // 等待 thread1 执行完毕
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println("线程 2 执行:" + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}

  • yield():静态方法,提示调度器当前线程愿意让出 CPU 资源,让其他具有相同优先级的线程有机会执行。但这只是一个建议,调度器可能会忽略该提示。
public class ThreadYieldExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("线程 1 执行:" + i);
                if (i == 2) {
                    Thread.yield(); // 线程 1 让出 CPU 资源
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("线程 2 执行:" + i);
            }
        });

        thread1.start();
        thread2.start();
    }
}

4. 线程的状态与优先级

  • getState():返回线程的当前状态,状态类型定义在 Thread.State 枚举中,包括 NEWRUNNABLEBLOCKEDWAITINGTIMED_WAITINGTERMINATED
public class ThreadStateExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("线程状态:" + thread.getState()); // 输出 NEW
        thread.start();
        System.out.println("线程状态:" + thread.getState()); // 可能输出 RUNNABLE 或 TIMED_WAITING
    }
}

  • getPriority():返回线程的优先级,范围是 1(最低优先级)到 10(最高优先级),默认优先级是 5。
  • setPriority(int newPriority):设置线程的优先级,可能会影响线程调度的顺序,但不能保证绝对的执行顺序。
public class ThreadPriorityExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("线程 1 执行:" + i);
            }
        });
        thread1.setPriority(Thread.MIN_PRIORITY); // 设置最低优先级

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("线程 2 执行:" + i);
            }
        });
        thread2.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级

        thread1.start();
        thread2.start();
    }
}

5. 线程的中断

  • interrupt():中断线程。如果线程处于阻塞状态(如 sleep()join()wait() 等),会抛出 InterruptedException 异常;如果线程未处于阻塞状态,中断标志会被设置为 true
  • isInterrupted():判断线程的中断标志是否被设置为 true
  • interrupted():静态方法,判断当前线程的中断标志是否被设置为 true,并清除中断标志。
public class ThreadInterruptExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("线程正在执行");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    System.out.println("线程被中断,中断标志:" + Thread.currentThread().isInterrupted());
                    Thread.currentThread().interrupt(); // 重新设置中断标志
                }
            }
            System.out.println("线程停止执行,中断标志:" + Thread.currentThread().isInterrupted());
        });

        thread.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt(); // 中断线程
    }
}

6. 线程的其他方法

  • currentThread():静态方法,返回当前正在执行的线程对象。
public class CurrentThreadExample {
    public static void main(String[] args) {
        Thread currentThread = Thread.currentThread();
        System.out.println("当前线程名:" + currentThread.getName());
    }
}

  • setName(String name):设置线程的名称。
  • getName():返回线程的名称。
public class ThreadNameExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("线程名:" + Thread.currentThread().getName());
        });
        thread.setName("MyThread");
        thread.start();
    }
}

这些方法可以帮助你更好地控制和管理线程的执行,根据不同的需求选择合适的方法来实现线程的各种功能。

JUC编程 文章被收录于专栏

JUC 是 Java.util.concurrent 包的简称,它是 Java 5 引入的一个用于处理并发编程的工具包,为 Java 开发者提供了一系列用于高效处理并发任务的类和接口,极大地简化了多线程编程的复杂性。

全部评论

相关推荐

GET请求和POST请求是HTTP协议中最常用的两种请求方法。https://www.nowcoder.com/issue/tutorial?zhuanlanId=Mg58Em&amp;amp;uuid=b48bebe08e474db8b80b853b12bafd48GET请求用于从服务器获取指定资源的数据。当浏览器请求一个URL时,它通常发送一个GET请求。GET请求的参数是在请求的URL中以查询字符串的形式发送的。这些参数可以通过在URL中添加键值对来传递给服务器。GET请求是幂等的,也就是说多次发送相同的GET请求不会对服务器产生任何副作用,并且可以被缓存。POST请求用于向服务器提交数据,例如表单数据。POST请求的参数是通过请求正文发送的,而不是直接在URL中传递。POST请求可以发送大量数据,且不会像GET请求那样对URL长度有限制。POST请求不是幂等的,多次发送相同的POST请求可能会导致服务器上的状态发生改变。GET和POST请求在以下方面存在区别:https://www.nowcoder.com/issue/tutorial?zhuanlanId=Mg58Em&amp;amp;uuid=b48bebe08e474db8b80b853b12bafd48参数传递方式:GET请求将参数以查询字符串的形式附加到URL上,而POST请求将参数放在请求正文中。数据体积:GET请求的数据大小受URL长度限制,通常用于获取少量数据;而POST请求可以发送大量数据。安全性:GET请求将参数暴露在URL中,因此不适合传输敏感数据;POST请求将参数放在请求正文中,相对更安全。幂等性:GET请求是幂等的,多次发送相同的GET请求不会对服务器产生任何副作用;POST请求不是幂等的,多次发送相同的POST请求可能会导致服务器状态改变。
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务