Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the core mechanism of Java threads?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the core mechanism of Java threads". In daily operation, I believe that many people have doubts about what the core mechanism of Java threads is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the core mechanism of Java threads?" Next, please follow the editor to study!

1. Basic mechanism of thread 1. Concept description

The characteristic of concurrent programming is that the program can be divided into multiple separate and independent tasks, and these independent tasks can be driven by threads, so as to improve the overall efficiency. A basic demonstration is provided below.

2. Application case

Scenario: suppose there is a collection of containers, and each element in the container needs to be taken out for processing. In general, it is good to traverse directly. If the data is too large, the collection can be cut according to the number of threads, and each thread processes part of the data. In this way, the processing time will be greatly reduced.

Public class ExtendThread01 {public static void main (String [] args) {List dataList = new ArrayList (); dataList.add ("A"); dataList.add ("B"); dataList.add ("C"); / / cut a large set according to two elements of each subset List splitList = splitList (dataList,2) For (List list:splitList) {System.out.println (list);} / / Multithreaded for (List childList:splitList) {ListTask listTask = new ListTask (childList); Thread runThread = new Thread (listTask); runThread.start () }} / * List collection cutting * / private static List splitList (List list, int childSize) {if (list = = null | | list.size () = = 0 | | childSize

< 1) { return null; } List result = new ArrayList(); int size = list.size(); int count = (size + childSize - 1) / childSize ; for (int i = 0; i < count; i++) { List subList = list.subList(i * childSize, ((i + 1) * childSize >

Size? Size: childSize * (I + 1)); result.add (subList);} return result;}} class ListTask implements Runnable {private List list; public ListTask (List list) {this.list=list;} @ Override public void run () {for (Object object:list) {System.out.println (Thread.currentThread (). GetName () + "=" + object);}

Note: the case here is just an implementation of the principle of the scenario, which is not allowed in development and needs to be handled by thread pool, as we will say later. If the collection is not properly controlled, a large number of Thread threads will be created, resulting in a memory overflow.

2. Thread stops and starts. 1. Basic process

The thread executes the task method after startup, which can be blocked, dormant, awakened, stopped and a series of state operations during execution.

Thread hibernation: when a thread enters a dormant (blocking) state after a part of the task has been executed, the thread scheduler can switch to another thread, which is relatively fair to the execution of distributed tasks.

2. Use case public class ExtendThread02 {public static void main (String [] args) {StopThread stopThread = new StopThread (); stopThread.start (); / / marks the current thread stop signal and throws an interrupt exception, but does not stop stopThread.interrupt (); / / determines whether the current thread is already in the termination state System.out.println ("1thread =" + stopThread.isInterrupted ()). / clear the termination signal of the current thread System.out.println ("2thread =" + stopThread.interrupted ()); / / determine the current thread status again System.out.println ("3thread =" + stopThread.isInterrupted ()); System.out.println ("main end...");}} class StopThread extends Thread {@ Override public void run () {for (int I = 0; I < 10) Try {System.out.println (Thread.currentThread (). GetId () + "=" + I); / / Thread blocking for 1 second Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} 3, Core method

Sleep (long millis): thread sleeps for a specified time and enters a blocking state

Interrupt (): switch the thread to the interrupt state, throw an interrupt exception, and do not stop the thread. You can monitor the interrupt state of the thread and define the execution policy.

Interrupted (): clears the interrupted state of the thread calling the method, does not affect the thread's execution, and returns whether the thread currently executing 'stopThread.interrupted ()' is interrupted, in this case, whether the main thread is interrupted.

IsInterrupted (): determines whether the thread calling the method is already in an interrupted state.

Make up a knife: these methods of the thread are extremely easy to be confused, need to break point source code tracking to see, enter the source code method, call the relevant API to check the status. (a picture of breakpoints is attached:)

Thread priority 1. Basic concepts

The order in which CPU executes and processes threads is uncertain, but thread schedulers tend to execute threads with high thread priority. High thread priority means a high probability of obtaining CPU resources, or obtaining more execution time fragments, but does not represent the last execution of a low priority thread.

2. Use case public class ExtendThread03 {public static void main (String [] args) {Priority01 priority01= new Priority01 (); priority01.start (); System.out.println ("priority01=" + priority01.getPriority ()); Priority02 priority02= new Priority02 (); priority02.start (); System.out.println ("priority02=" + priority02.getPriority ()); priority01.setPriority (10); priority02.setPriority (1) }} class Priority01 extends Thread {@ Override public void run () {for (int I = 0; I < 100m +) {System.out.println (Thread.currentThread (). GetName () + "; I =" + I);} class Priority02 extends Thread {@ Override public void run () {for (int a = 0; a < 100) ) {System.out.println (Thread.currentThread () .getName () + "; a =" + a);}

Note: priority range [MAX_PRIORITY=10,MIN_PRIORITY=1]. If it is out of range, an IllegalArgumentException exception will be thrown.

Suggestion: usually in actual development, it is not allowed to easily modify the parameters of the thread, which is easy to cause exceptions beyond cognition.

4. Thread addition 1. Basic concepts

If thread An executes the join method of thread B, then thread A waits for thread B to finish execution before returning to continue execution.

2. Use case public class ExtendThread04 {public static void main (String [] args) {JoinThreadA joinThreadA = new JoinThreadA (); joinThreadA.start ();}} class JoinThreadA extends Thread {@ Override public void run () {System.out.println ("in lack of water..."); JoinThreadB joinThreadB = new JoinThreadB (); joinThreadB.start (); try {joinThreadB.join () } catch (Exception e) {e.printStackTrace ();} System.out.println ("drinking water...");}} class JoinThreadB extends Thread {@ Override public void run () {System.out.println ("buy water..."); try {TimeUnit.SECONDS.sleep (2) } catch (Exception e) {e.printStackTrace ();} System.out.println ("buy water...");}}

Note: you can set the thread join time join (long), after all, can not wait for the snow moon wind, life is sometimes poor, can only be indefinite later.

5. Local thread 1. Basic concepts

Local thread variables, the underlying maintenance ThreadLocalMap stored values:

Static class Entry extends WeakReference

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report