s1线程-thread

本文详细介绍了Java线程的创建(Thread子类和Runnable接口)、线程的主要方法,包括生命周期中的状态(NEW、RUNNABLE、BLOCKED、WAITING/TIMED_WAITING、TERMINATED)及中断机制。通过示例代码展示了如何中断线程以及守护线程的概念。此外,还讨论了yield()、join()和sleep()等易混淆的方法。
摘要由CSDN通过智能技术生成

why

你好! 一直使用java线程,准备一步一步深入她!线程是程序中执行的线程。java虚拟机允许应用程序有多个线程并行执行。每个线程都有一个优先级。

实现的两种方法:

  • 将类声明为Thread的子类
  • 声明类实现Runnable接口

主要包含的方法:

  • static native Thread currentThread(); 返回对当前正在执行的线程对象的引用。
  • long getId()返回该线程的标识符。
  • final String getName()返回该线程的名称。
  • final int getPriority()返回线程的优先级。
  • void interrupt() 中断线程。
  • final native boolean isAlive();测试线程是否处于活动状态。
  • final void join() throws InterruptedException等待该线程终止。
  • final synchronized void join(long millis) throws InterruptedException等待该线程终止的时间最长为 millis 毫秒。
  • final synchronized void join(long millis, int nanos) throws InterruptedException 等待该线程终止的时间最长为 millis 毫秒 + nanos 纳秒。
  • final void setDaemon(boolean on)将该线程标记为守护线程或用户线程。
  • final void setPriority(int newPriority) 更改线程的优先级。
  • static native void sleep(long millis) throws InterruptedException;在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。
  • static void sleep(long millis, int nanos)throws InterruptedException 在指定的毫秒数加指定的纳秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。
  • synchronized void start()使该线程开始执行;Java 虚拟机调用该线程的 run 方法。
  • static native void yield();暂停当前正在执行的线程对象,并执行其他线程。

生命周期中的状态State

  • NEW 线程还没有开始
  • RUNNABLE 是可运行状态,在java虚拟机里执行,但是可能在等待其它操作系统资源,比如:processor
  • BLOCKED 阻塞等待进入monitor lock.to enter/reenter synchronized block/method
  • WAITING 等待另一个线程进入某种特定行为,比如
    1, 当前线程wait() ,然后等待另一线程执行notify()
    2, 当前线程Thread.join() 等待特定线程结束
  • TIMED_WAITING 等待特定时间的线程状态。当前的方法:
sleep #Thread.sleep(long)
wait # Object.wait(long)
join # Thread.join(long)
LockSupport#LockSupport.parkNanos(long)
LockSupport#LockSupport.parkUntil()
  • TERMINATED 终止线程,已经完全执行

中断线程

  • interrupt()方法
  • 设置标志位。running标志位来标识线程是否应该继续运行

目标线程检测到isInterrupted()为true或者捕获了InterruptedException都应该立刻结束自身线程

demo1

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new MyThread();
        t.start();
        Thread.sleep(1000);
        t.interrupt(); // 中断t线程
        t.join(); // 等待t线程结束
        System.out.println("end");
    }
}

class MyThread extends Thread {
    public void run() {
        Thread hello = new HelloThread();
        hello.start(); // 启动hello线程
        try {
            hello.join(); // 等待hello线程结束
        } catch (InterruptedException e) {
            System.out.println("interrupted!");
        }
        hello.interrupt();
    }
}

class HelloThread extends Thread {
    public void run() {
        int n = 0;
        while (!isInterrupted()) {
            n++;
            System.out.println(n + " hello!");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
}

demo2

public class Main {
    public static void main(String[] args)  throws InterruptedException {
        HelloThread t = new HelloThread();
        t.start();
        Thread.sleep(1);
        t.running = false; // 标志位置为false
    }
}

class HelloThread extends Thread {
    public volatile boolean running = true;
    public void run() {
        int n = 0;
        while (running) {
            n ++;
            System.out.println(n + " hello!");
        }
        System.out.println("end!");
    }
}

守护线程

守护线程是为其他线程服务的线程;
所有非守护线程都执行完毕后,虚拟机退出;
守护线程不能持有需要关闭的资源(如打开文件等)。

易混淆方法

  1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.

如果没有低于自己优先级的线程,继续执行。不建议使用

  1. join() If any executing thread t1 calls join() on t2 (i.e. t2.join()) immediately t1 will enter into waiting state until t2 completes its execution.

千年等一回

  1. sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).

对于我们最喜欢的方法,不作解释

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值