In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I would like to share with you the basic knowledge of Java concurrent programming what are the relevant knowledge points, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's learn about it.
01. Introduction
First of all, or to understand the basis of threads, this article will take you to understand the basics of threads.
02. How to create a thread
Implement the Runnable interface
Inherit the Thread class
Implement the Callable interface to create threads through the FutureTask wrapper
Create a thread through a thread pool
The thread is created in the form of thread pool and Callable
Public class CallableDemo implements Callable {@ Override public String call () throws Exception {int aquifers 1; int bread2; System. Out .println (aqb); return "execution result:" + (aqb);} public static void main (String [] args) throws ExecutionException, InterruptedException {/ / create a thread pool with a reusable fixed number of threads ExecutorService executorService = Executors.newFixedThreadPool (1); CallableDemo callableDemo=new CallableDemo (); / / execute thread, using future to receive thread return value Future future = executorService.submit (callableDemo) / / the return value of the print thread System. Out .println (future.get ()); executorService.shutdown ();}}
Execution result
3 execution result: 303, thread life cycle
NEW: initial state, the thread is built, but the start method has not been called yet.
RUNNABLED: running state, the JAVA thread refers to the ready and running states in the operating system as "running". Call the thread's start () method to get the thread into a ready state.
BLOCKED: blocking state, indicating that the thread has entered a waiting state, that is, the thread has given up the right to use CPU for some reason. For example, the method that accesses the synchronized keyword modification does not acquire an object lock.
Waiting: wait state, such as calling the wait () method.
TIME_WAITING: timeout waiting status, which is returned automatically after timeout. For example, call the sleep (long millis) method
TERMINATED: termination status, indicating that the current thread has finished executing.
Look at the source code:
Public enum State {NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;} 04, priority of the thread
Minimum priority of the thread: 1
Maximum priority of the thread: 10
Default priority for threads: 5
Get and set the priority of the thread by calling the getPriority () and setPriority (int newPriority) methods
Look at the source code:
/ * The minimum priority that a thread can have. * / public final static int MIN_PRIORITY = 1; / * * The default priority that is assigned to a thread. * / public final static int NORM_PRIORITY = 5; / * * The maximum priority that a thread can have. * / public final static int MAX_PRIORITY = 10
Take a look at the code:
Public class ThreadA extends Thread {public static void main (String [] args) {ThreadA a = new ThreadA (); System.out.println (a.getPriority ()); / / 5 a.setPriority (8); System.out.println (a.getPriority ()); / / 8}}
Thread priority feature:
Inheritance: for example, if thread A starts thread B, thread B has the same priority as thread A.
Regularity: most of the high-priority threads finish first, but that doesn't mean all the high-priority threads finish first.
Randomness: higher priority threads do not necessarily finish execution every time.
05. Stop of thread
The stop () method, which has been marked obsolete, forces the thread to stop, which is equivalent to kill-9.
The interrupt () method gracefully stops the thread. Tells the thread that it can stop, and when the thread stops depends on the thread itself.
Take a look at the code that stops the thread:
Public class InterruptDemo {private static int i; public static void main (String [] args) throws InterruptedException {Thread thread = new Thread (()-> {/ / by default isInterrupted returns false and becomes true while (! Thread.currentThread (). IsInterrupted ()) through thread.interrupt. System.out.println ("Num:" + I) }, "interruptDemo"); thread.start (); TimeUnit.SECONDS.sleep (1); thread.interrupt (); / / without this sentence, the thread thread will not stop}}
Looking at the above code, the main thread main method calls the interrupt () method of the thread thread, telling the thread thread that you can stop (actually setting a property of the thread thread to true), and then the thread thread gets this property through the isInterrupted () method to determine whether it is set to true. Let me give you another example to illustrate.
Look at the code:
Public class ThreadDemo {private volatile static Boolean interrupt = false; private static int i; public static void main (String [] args) throws InterruptedException {Thread thread = new Thread (()-> {while (! interrupt) {ionization;} System.out.println ("Num:" + I);}, "ThreadDemo"); thread.start () TimeUnit.SECONDS.sleep (1); interrupt = true;}}
Is it very similar? let's briefly sum up:
When another thread calls the interrupt method of the current thread, it says hello to the current thread and tells him that it can interrupt the execution of the thread and will not interrupt the thread immediately. When to interrupt depends on the current thread itself.
Threads respond by checking whether they are interrupted or not, and can determine whether they are interrupted by isInterrupted ().
This way of implementing the interrupt operation through the identifier can give the thread the opportunity to clean up the resources at the time of termination, rather than arbitrarily stop the thread, so this way of terminating the thread is more safe and elegant.
06. Thread reset
There are two ways to reset:
Thread.interrupted ()
By throwing an InterruptedException
Then learn what a reset is:
When the thread is running, Thread.isInterrupted () returns the thread state as false, and then calls thread.interrupt () to interrupt the thread Thread.isInterrupted () to return the thread state as true, and finally calls Thread.interrupted () to reset the thread Thread.isInterrupted () to return the thread state to false or before throwing an InterruptedException exception, the thread will set the state to false.
Let's take a look at the code for resetting the thread in two ways, first of all, the reset code for Thread.interrupted ():
Public class InterruptDemo {public static void main (String [] args) throws InterruptedException {Thread thread = new Thread (()-> {while (true) {/ / Thread.currentThread () .isInterrupted () defaults to false, when thread.interrupt () is executed in main mode The status is changed to true if (Thread.currentThread () .isInterrupted ()) {System.out.println ("before:" + Thread.currentThread () .isInterrupted ()) / / before:true Thread.interrupted (); / / A pair of threads are reset from true to false System.out.println ("after:" + Thread.currentThread (). IsInterrupted ()); / / after:false}, "interruptDemo"); thread.start (); TimeUnit.SECONDS.sleep (1) Thread.interrupt ();}}
Throw the InterruptedException reset thread code:
Public class InterruptedExceptionDemo {public static void main (String [] args) throws InterruptedException {Thread thread = new Thread (()-> {while (! Thread.currentThread (). IsInterrupted ()) {try {TimeUnit.SECONDS.sleep (1);} catch (InterruptedException e) {e.printStackTrace () / / break;}, "interruptDemo"); thread.start (); TimeUnit.SECONDS.sleep (1); thread.interrupt (); System.out.println (thread.isInterrupted ());}}
Results:
False java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep (Native Method) at java.lang.Thread.sleep (Thread.java:340) at java.util.concurrent.TimeUnit.sleep (TimeUnit.java:386) at com.cl.concurrentprogram.InterruptedExceptionDemo.lambda$main$0 (InterruptedExceptionDemo.java:16) at java.lang.Thread.run (Thread.java:748)
It should be noted that the throwing of an InterruptedException exception does not mean that the thread must be terminated, but rather that the current thread is reminded of an interrupted operation, and what to do next depends on the thread itself, such as
Catch exceptions directly without doing any processing
Throw an exception out
Stop the current thread and print the exception message
As in my example above, if an InterruptedException exception is thrown, I break out of the loop and let the thread thread terminate.
Why reset:
Thread.interrupted () belongs to the current thread and is a response of the current thread to the external interrupt signal, indicating that it has received the interrupt signal, but will not interrupt itself immediately. It is up to the outside world to decide when to interrupt and let the outside world know that before its own interrupt, its interrupt state is still false, which is the reason for the reset.
That's all of the article "what are the basics of Java concurrent programming?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.