In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "what are the commonly used operations in Java threads". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Common operations of threads
Set thread name: setName ()
Get thread name: getName ()
Thread unique Id:getId ()
/ / Custom thread name String threadName = "threadName"; / / Construction method Thread thread = new Thread (()-> {System.out.println ("thread name =" thread name = "Thread.currentThread (). GetName ());}, threadName); / / set method method / / thread.setName (threadName); System.out.println (" thread unique Id= "+ thread.getId ())
Thread startup: start ()
Determine whether the thread survives: isAlive ()
/ / Thread starts thread.start (); System.out.println ("whether it is a surviving thread =" + thread.isAlive ())
Thread method: run () / call ()
The method that will be called after the thread starts. What the thread wants to do is written in the run/call method. It doesn't need to be called directly. After the thread starts, it will call run () / call (). If the program does not start the thread to call run/call directly, then it does not belong to multithreaded programming, but belongs to the current thread directly calling the ordinary method.
Get the current thread object: currentThread ()
To manipulate the non-static method of the current thread, you must get the thread object first.
/ / get the current thread object Thread currentThread = Thread.currentThread (); / / do some operations on the current thread System.out.println (currentThread.getName ()); try {/ / sleep static methods do not require Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();}
For operations on thread state control (life cycle), you can refer to the previous article.
Daemon thread (backstage thread)
The guardian of an ordinary thread (user thread), whose task is to provide services to other threads. If there is no user thread in the process, there is no point in the daemon thread, and the JVM ends. A typical daemon thread is JVM's garbage collection thread, and the startup of the operating system will also start the daemon thread of various modules.
Set the thread as a daemon thread: setDaeman ()
Note: this method must be called before the start () method
Public static void main (String [] args) {Thread thread = new Thread (()-> {System.out.println ("thread name =" Thread.currentThread () .getName ()); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ()) } / / this sentence will not be printed because the main thread (currently the only ordinary thread) has finished System.out.println ("daemon thread state =" + Thread.currentThread (). GetState ()) after waiting for 1 second; / / daemon thread thread.setDaemon (true); / / thread starts thread.start () System.out.println ("whether it is a daemon thread =" + thread.isDaemon ());} thread serialization
The thread executing the join () method enters the wakeup state (WAITING) until the end of the thread calling the method, and then changes from the wakeup state to the runnable state (RUNNABLE). The join () method is a method in the Thread class, whose bottom layer is to use the wait () method to implement thread waiting until the thread isAlive () is false.
Implement thread serialization: one thread calls the join () of another thread object to implement thread serialization execution.
For example: a good dish
Public class DemoCooking {public static void main (String [] args) {Thread mainThread = Thread.currentThread (); / / 1. Thread buyThread = new Thread (new CookingThread (mainThread, "buy vegetables"), "buyThread"); / / 2. Thread washThread = new Thread (new CookingThread (buyThread, "washing vegetables"), "washThread"); / / 3. Thread cutThread = new Thread (new CookingThread (washThread, "cut vegetables"), "cutThread"); / / 4. Stir-fry Thread scrambleThread = new Thread (new CookingThread (cutThread, "stir-fry"), "scrambleThread"); / / it is not affected by the thread startup order scrambleThread.start (); washThread.start (); cutThread.start (); buyThread.start (); / / the main thread finishes execution before it starts: buy vegetable System.out.println ("start preparing.") Public static class CookingThread implements Runnable {private final Thread thread; private final String job; public CookingThread (Thread thread, String job) {this.thread = thread; this.job = job;} @ Override public void run () {String name = Thread.currentThread () .getName () + ":" Try {thread.join (); System.out.println (name + job + "start"); Thread.sleep (1000); System.out.println (name + job + "end"); Thread.sleep (1000) / / lazy} catch (InterruptedException e) {e.printStackTrace ();}
Execution result: main > buyThread > washThread > cutThread > scrambleThread > end
Begin to prepare for.
BuyThread: start shopping
BuyThread: the end of shopping
WashThread: start washing vegetables
WashThread: after washing vegetables
CutThread: start cutting vegetables
CutThread: the end of cutting vegetables
ScrambleThread: stir-fry
ScrambleThread: the cooking is over.
Thread priority
Set the priority of the current thread, the higher the priority of the thread, the more times the thread is likely to be executed. The priority of the Java thread is expressed as an integer, with a priority range of 1-10 and a default of 5.
The setPriority (int) method: sets the priority of the thread.
The getPriority method: gets the priority of the thread.
Public static void main (String [] args) {Thread thread = new Thread (()-> {System.out.println (Thread 1);}); thread.setPriority (10); Thread thread1 = new Thread (()-> {System.out.println (Thread 2);}); thread1.setPriority (1); thread.start (); thread1.start () System.out.println ("default priority of thread is =" + Thread.currentThread () .getPriority ());} thread interrupt
Use the interrupt () method to set the thread interrupt flag = true to throw an interrupt signal when the thread is "blocked". If a thread is in a blocking, waking up, or timeout wait state (Object.wait, Thread.join, and Thread.sleep), it will receive an interrupt exception (InterruptedException) and end the state prematurely. Conversely, if the thread is in a "RUNNABLE" state, the interrupt flag will have no effect.
Case 1: thread interrupt is valid
Public static void main (String [] args) {Thread thread = new Thread (()-> {System.out.println ("Thread 1"); try {/ / alarm clock rings in 1 minute Thread.sleep (60000); System.out.println ("alarm clock goes off") } catch (InterruptedException e) {/ / early exit timeout waiting status System.out.println ("an exception occurred, woke up early, the alarm clock did not ring and manually turned off");} System.out.println ("continue to execute the subsequent program of this thread …") ;}); thread.setPriority (1); thread.start (); thread.interrupt (); System.out.println ("mainthread sets thread terminal status to" + thread.isInterrupted ());}
Execution result:
The main thread sets the thread terminal state to true
Thread 1
There was an exception. I woke up early. The alarm clock didn't go off and turned off manually.
Continue to execute the subsequent programs of this thread.
Case 2: invalid thread interrupt
Public static void main (String [] args) {Thread thread1 = new Thread (()-> {System.out.println ("thread" + Thread.currentThread (). GetName ()); while (true) {System.out.print (Thread.currentThread (). GetState () + "\ t");}}); thread1.start (); thread1.interrupt ();}
Execution result: the thread always prints its own status as RUNNABLE.
This is the end of the content of "what are the common operations in Java threads?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.