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

Example Analysis of processes and Threads in JUC concurrent programming

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

Share

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

This article will explain in detail the example analysis of processes and threads in JUC concurrent programming. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Processes and threaded processes

The program consists of instructions and data, but in order to run these instructions and read and write the data, you must load the instructions into CPU and the data into memory. Disk, network and other devices are also needed in the process of instruction operation. Processes are used to load instructions, manage memory, and manage IO

When a program is run and the program's code is loaded from disk into memory, a process is started.

The process can be regarded as an instance of the program. Most programs can run multiple instance processes at the same time (such as notepad, drawing, browser, etc.), while some programs can only start one instance process (such as NetEyun Music, 360 Security Guards, etc.)

Thread

The thread is mainly responsible for running the instruction, and the process is the main tube for loading the instruction.

A process can be divided into one or more threads.

A thread is an instruction stream that sends instructions in the instruction stream to CPU for execution in a certain order.

In Java, the thread is the minimum scheduling unit, and the process is the smallest unit of resource allocation. In windows, a process is inactive, just as a container for threads

Synchronous and asynchronous

You need to wait for the result to return before you can continue to run is synchronization.

It is asynchronous to continue running without waiting for the result to return.

Serial parallel execution time

Using multi-core cpu parallel execution can obviously improve the execution efficiency.

Serial execution time = cumulative time of each thread and + summary time

Parallel execution time = slowest thread time + summary time

Note: single core is still the idea of concurrency (that is, cpu takes turns to execute threads, microscopically it is still serial), and multithreading with a single core may be slower than a single thread with a single core, because multithreading context switching is a waste of time.

Create and run threads

1. Use Thread

Public static void main (String [] args) {/ / create thread object Thread t = new Thread ("Thread 1") {public void run () {/ / Task to be executed log.debug ("Thread 1 is started");}}; / / start thread t.start () Log.debug (Test);}

two。 Use Runnable with Thread

Public static void main (String [] args) {Runnable runnable = new Runnable () {public void run () {/ / the task to be executed log.debug ("Thread 1 is started");}}; / / create thread object Thread t = new Thread (runnable); t.setName ("Thread 1") / / start thread t.start (); log.debug ("test");}

The Runnable here is an interface, and there is only one abstract method in the interface. We provide the implementation, and the thread code is included in the implementation.

@ FunctionalInterfacepublic interface Runnable {/ * * When an object implementing interface Runnable is used * to create a thread, starting the thread causes the object's * run method to be called in that separately executing * thread. *

* The general contract of the method run is that it may * take any action whatsoever. * * @ see java.lang.Thread#run () * / public abstract void run ();} principle Analysis of the relationship between Thread and Runnable

Method 1 principle analysis

Method 2 uses the runnable object and passes it to the Thread constructor as a parameter, in which the init method is called. Here is the source code of the Thread constructor

Public Thread (Runnable target) {init (null, target, "Thread-" + nextThreadNum (), 0);}

Continue to trace where the runnable object is passed, and you can see that it has been passed to another overloaded init, as follows

Private void init (ThreadGroup g, Runnable target, String name, long stackSize) {init (g, target, name, stackSize, null, true);} private void init (ThreadGroup g, Runnable target, String name, long stackSize) {init (g, target, name, stackSize, null, true);}

Once again, you can see that the runnable object is passed to a member variable of a thread.

/ / omit part of the code this.target = target

So where is this member variable used? after searching, it can be found that it is in the run method, but when Thread finds that there is a runnable object, it will first use the run method of runnable.

Override public void run () {if (target! = null) {target.run ();}}

Method 2 principle analysis

Override the run method of the Thread class by creating a subclass so that the run method of the parent class is not executed.

1. It is easier to cooperate with advanced API such as thread pool with Runnable.

two。 Use Runnable to make the task class more flexible than the Thread inheritance system.

Method 3 FutureTask cooperates with Thread to create thread

The Future interface contains the get method to return the result

/ / omit some codes V get () throws InterruptedException, ExecutionException;V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

Runnable itself does not return a result, and runnable cannot pass the result to other threads.

Public interface Runnable {public abstract void run ();}

Note that FutureTask also implements the Runnable interface and can also be passed to the parameter construct of Thread.

The code that creates the thread

Public static void main (String [] args) throws ExecutionException, InterruptedException {/ / create task object FutureTask task3 = new FutureTask (new Callable () {@ Override public Integer call () throws Exception {log.debug ("Thread 1 is executed"); return 666;}}); / / Parameter 1 is the task object Parameter 2 is the name of the thread, recommended new Thread (task3, "thread 1"). Start (); / / main thread blocking, synchronously waiting for the result of task execution completed Integer result = task3.get (); log.debug ("result: {}", result);} View the process

The task manager can view the number of processes and threads, and can also be used to kill processes. You can also use tasklist to view the process taskkill on the console to kill processes.

Jconsole remote monitoring configuration to view

Principle of thread operation

JVM consists of a stack, a stack, and a method area, where the stack is for threads to use.

When a method is called, a stack frame is generated for the method, and the local variables of the method are stored in the stack frame. The stack is last-in, first-out, and will be recycled when the method2 is finished, and the return address will be recorded at the same time, and then continue execution in the method1.

The stack frames between threads are independent of each other and do not interfere with each other.

Thread context switch

When the context is switched, save the current state, because the time slice may be used up and the thread has not finished yet. The corresponding program counter in Java

Start and run method

To start a thread, you must use the start method. If you directly call the run method in the class, you are actually going through the main main thread.

The thread getState () before start gets NEW.

What getState () gets after the thread start is RUNNABLE

Public static void main (String [] args) {Thread T1 = new Thread ("T1") {@ Override public void run () {log.debug ("T1 is started"); System.out.println (t1.getState ()); t1.start (); System.out.println (t1.getState ());} sleep method

You can get TIMED_WAITING by calling the getState () method during sleep

Public static void main (String [] args) {Thread T1 = new Thread ("Thread 1") {@ Override public void run () {try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} T1.start (); log.debug ("thread 1 state: {}", t1.getState ()); try {Thread.sleep (500);} catch (InterruptedException e) {e.printStackTrace ();} log.debug ("thread 1 state: {}", t1.getState ());} sleep interrupt

Sleep can be interrupted using the interrupt method, which triggers an InterruptedException exception

Public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread ("T1") {@ Override public void run () {log.debug ("sleep"); try {Thread.sleep (2000) } catch (InterruptedException e) {log.debug ("Wake up"); e.printStackTrace ();}; t1.start (); Thread.sleep (1000); log.debug ("interrupt"); t1.interrupt ();}

Sleep prevents cpu from using 100%

Don't let while (true) idle waste cpu when you don't use cpu to calculate. You can use yield or sleep to give up the right to use cpu to other programs.

The yield method gives up the right to use the cpu, and then schedules the execution of other threads. The scheduling of threads ultimately depends on the scheduler of the operating system.

Join method

This method waits for the end of the thread

Static int r = 11; public static void main (String [] args) throws InterruptedException {test1 ();} private static void test1 () throws InterruptedException {log.debug ("main thread start"); Thread T1 = new Thread (()-> {sleep (1); r = 888;}, "Thread 1"); t1.start (); / / t1.join () Log.debug (String.valueOf (r)); log.debug ("main thread ends");}

When join is not in use, 11 is returned. If join is used, 888 is returned, and the main thread is synchronously waiting for thread 1.

Of course, there are other ways to wait.

The 1.sleep method waits for thread 1 to finish

two。 Using the get method of FutureTask

The join (long n) method can pass in parameters to wait for the thread to finish running, waiting for up to n milliseconds. If the execution time is longer than the waiting time, it will no longer wait. So will the thread end directly? The answer is no.

The code is as follows

Public class Test10 {static int r = 11; public static void main (String [] args) throws InterruptedException {test1 ();} private static void test1 () throws InterruptedException {log.debug ("main thread start"); Thread T1 = new Thread (()-> {sleep (2); r = 888; log.debug ("thread 1 ends") }, "Thread 1"); t1.start (); t1.join (1000); log.debug (String.valueOf (r)); log.debug ("main thread ends");}}

As you can see from the output, it's just that the main thread is no longer waiting.

16 28 53.360 c.Test10 [main]-the main thread starts

16purl 28purl 54.411 c.Test10 [main]-11

16blog 28purl 54.411 c.Test10 [main]-end of main thread thread

16VOV 28RU 55.404 c.Test10 [Thread 1]-Thread 1 ends

Interrupt method

Interrupt can be used to break threads in a blocked state. After a break, there will be a break flag (Boolean value) that prompts you if it has been interrupted. If it has been interrupted, it is marked true or false.

But sleep, wait, and join can clear the break tag.

The code is as follows

Public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread (()-> {log.debug ("sleep..."); try {Thread.sleep (4000);} catch (InterruptedException e) {e.printStackTrace ();}}, "T1"); t1.start () Thread.sleep (1000); log.debug ("interrupt"); t1.interrupt (); log.debug ("break Mark: {}", t1.isInterrupted ());}

The thread will not stop running after it is interrupted, and some people will ask, how can we shut down the thread after interrupting the thread? The answer is to use the break mark to achieve it.

It can be implemented by adding a judgment to the thread's dead loop.

Boolean interrupted = Thread.currentThread () .isInterrupted (); if (interrupted) {log.debug ("exit loop"); break;} daemon

The Java process usually ends when all threads are running.

But there is a daemon that ends as long as other non-daemons end. The daemon used by the garbage collector.

The state of the thread

Operating system level (state of early processes)

The initial state creates a thread object at the language level and is not yet associated with the operating system thread

Runnable state (ready state) means that the thread has been created (associated with the operating system thread) and can be scheduled and executed by CPU.

The running status acquires the running status of the CPU time slice

Call blocking api to change the running state to blocking state

The termination status indicates that the thread has finished execution

Java API level

1. Create a new status (New)

Thread T1 = new Thread ("T1") {@ Override public void run () {log.debug ("running...");}}; log.debug ("T1 state {}", t1.getState ())

2. Ready state (Runnable) and running state (Running)

Thread T2 = new Thread ("T2") {@ Override public void run () {while (true) {/ / runnable}; t2.start (); log.debug ("T2 state {}", t2.getState ())

3. Blocking status (Blocked)

Use a thread to get the lock, so that the current thread does not get the lock will be blocked.

Thread T6 = new Thread ("T6") {@ Override public void run () {synchronized (TestState.class) {/ / blocked try {Thread.sleep (90000);} catch (InterruptedException e) {e.printStackTrace () }; t6.start ()

4. Wait status (Waiting)

Wait for a thread that has not completed execution

T2.join (); / / wait status

5. Time-out waiting (Time_Waiting)

You can return on your own at a specified time.

6. Termination status (TERMINATED)

The thread ends its life cycle when it finishes execution or exits the run () method because of an exception. The terminated thread cannot be revived again.

This is the end of this article on "sample analysis of processes and threads in JUC concurrent programming". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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