当前位置:网站首页>What common APIs are involved in thread state changes

What common APIs are involved in thread state changes

2022-06-25 07:24:00 Bug trendsetter

Basic thread mechanism

Executor

Manage the execution of multiple asynchronous tasks , Without programmers having to explicitly manage the life cycle of threads . Asynchrony here means that the execution of multiple tasks does not interfere with each other , No need to synchronize .

33c4c5f0460836ef4ed2bd7ac63b0b76.png

Daemon

Daemons are threads that provide services in the background when a program is running , Not an integral part of the program .
When all non - daemons end , And the program ends , It will kill all the daemons at the same time .
main() Belongs to non daemonic thread .
Use setDaemon() Method to set a thread as a guardian thread .

public  static  void main(String[] args) {
     Thread thread =  new Thread(new MyRunnable());
      thread.setDaemon(true);
}

sleep()

Thread.sleep(millisec) Method sleeps the currently executing thread ,millisec The unit is millisecond .

sleep() May throw InterruptedException, Because exceptions cannot be propagated back across threads main() in , So it has to be done locally . Other exceptions thrown in the thread also need to be handled locally .

public void run() {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

yield()

For static methods Thread.yield() The call to declare that the current thread has completed the most important part of its life cycle , You can switch to other threads to execute . This method is just a suggestion for thread scheduler , It is only recommended that other threads with the same priority can run .

public void run() {
    Thread.yield();
}

interrupt

A thread will automatically end after execution , If there is an exception in the running process, it will end ahead of time .

InterruptedException

By calling the interrupt() To interrupt the thread , If the thread is blocked 、 The state of waiting or waiting indefinitely , Then it will throw InterruptedException, So that the thread ends ahead of time . But it can't be interrupted I/O Blocking and synchronized The lock is blocked .

For the following code , stay main() Start a thread and interrupt it , Because the thread called Thread.sleep() Method , So a InterruptedException, So as to terminate the thread ahead of time , Do not execute subsequent statements .

public class InterruptExample {


    private static class MyThread1 extends Thread {
        @Override
        public void run() {
            try{
                Thread.sleep(2000);
                System.out.println("Thread run");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


public static void main(String[] args) throws InterruptedException {
    Thread thread1 = new MyThread1();
    thread1.start();
    thread1.interrupt();
    System.out.println("Main run");
}


// result 
Main run
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at InterruptExample.lambda$main$0(InterruptExample.java:5)
    at InterruptExample$$Lambda$1/713338599.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)

interrupted()

If a thread's run() Method to execute an infinite loop , And not implemented sleep() I'll throw it out later InterruptedException The operation of , Then call the thread's interrupt() Method does not allow the thread to end prematurely .

But the call interrupt() Method sets the thread's interrupt flag , Call at this time interrupted() Method will return true. So you can use interrupted() Method to determine whether the thread is in an interrupt state , So as to terminate the thread ahead of time .

public class InterruptExample {
    private static class MyThread2 extends Thread {
         @Override
        public void run() {
             while (!interrupted()) {
                  // ..
            }
            System.out.println("Thread end");
        }
    }
}


public static void main(String[] args) throws InterruptedException {
    Thread thread2 = new MyThread2();
    thread2.start();
    thread2.interrupt();
}


// result 
Thread end

Executor Interrupt operation of

call Executor Of shutdown() Method will wait for the thread to finish executing before closing , But if you call shutdownNow() Method , It is equivalent to calling the interrupt() Method .

The following uses Lambda Create thread , Equivalent to creating an anonymous internal thread .

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(() -> {
        try {
            Thread.sleep(2000);
            System.out.println("Thread run");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    executorService.shutdownNow();
    System.out.println("Main run");
}


// result 
Main run
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9)
    at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

If you just want to interrupt Executor One thread in , By using submit() Method to commit a thread , It will return one Future<?> object , By calling the cancel(true) Method to interrupt the thread .

Future<?> future = executorService.submit(() -> {
      // ..
});
future.cancel(true);

Remember to point 「 Fabulous 」 and 「 Looking at 」↓

Love you

原网站

版权声明
本文为[Bug trendsetter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250500043492.html