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

Four ways to create Thread Communication in Java

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this issue, the editor will bring you four ways to create thread communication in Java. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Catalogue

1.1 create thread

1.1.1 four ways to create threads

1.1.2 comparison between Thread class and Runnable interface

1.1.3 Callable, Future and FutureTask

1.2 Thread groups and thread priorities

1.3State of Java thread and its main transformation methods

1.4 Communication between Java threads

1.4.1 waiting / notification mechanism

1.4.2 semaphore

1.4.3 Pip

Summary

1.1 create Thread 1.1.1 four ways to create Thread

[1] inherit the Thread class

[2] implement Runnable interface

[3] implement Callable and get the return value

[4] implement the FutureTask class

The Thread class is an implementation class of the Runnable interface, and the Thread class is initialized by calling a private init.

G: thread group

Target: a threading class that implements the Runnable interface

Name: thread name, default Thread- random number if not specified

StackSize: thread initial stack size

1.1.2 comparison between Thread class and Runnable interface

1: because of Java's "single inheritance, multiple implementation" feature, the Runnable interface is more flexible to use than Thread.

The 2:Runnable interface appears to be more object-oriented, encapsulating the thread separately.

The emergence of the 3:Runnable interface reduces the coupling between thread objects and thread tasks.

4: if you don't need to use many of the methods of the Thread class when using threads, it's obviously lighter to use the Runnable interface. Thread is an object that extends the Runnable interface.

1.1.3 Callable, Future and FutureTask

Use Runnable and Thread to create a new thread. But they have the drawback that the run method does not return a value. Sometimes we want to start a thread to execute a task, and the task is completed with a return value.

@ FunctionalInterfacepublic interface Callable {/ * processes the task and returns a result * * @ return computed result * @ throws Exception if unable to compute a result * / V call () throws Exception;}

Callable is generally used in conjunction with the thread pool tool ExecutorService. ExecutorService can use the submit method to have a Callable interface execute. It returns a Future that we pass through

Future.get () can get the returned result of the thread execution.

1.2 Thread groups and thread priorities

Thread groups are represented by ThreadGroup in Java, and we can use thread groups to batch control threads.

The relationship between ThreadGroup and Thread is as simple and rough as their literal meaning. Each Thread must exist in a ThreadGroup, and Thread cannot exist independently of ThreadGroup. The name of the thread executing the main () method is main, and if it is not explicitly specified at new Thread, the thread group of the parent thread (the thread currently executing new Thread) is set to its own thread group by default.

ThreadGroup manages that the Thread,ThreadGroup below it is a standard downward referenced tree structure designed to prevent "superior" threads from being referenced by "subordinate" threads and cannot be effectively recycled by GC.

Thread priority can be specified in Java, with a range of 1-10. However, not all operating systems support a level 10 priority division (for example, some operating systems only support a level 3 division: low, medium, and high). Java only gives the operating system a reference value of priority, and the thread's final priority in the operating system is determined by the operating system.

The default thread priority of Java is 5, the execution order of threads is determined by the scheduler, and the priority of threads is set before the thread is called.

In general, high-priority threads will have a higher chance of execution than low-priority threads. We use the setPriority () instance method of the method Thread class to set the thread priority.

The priority in Java is not particularly reliable, and the priority set for threads in Java programs is only a suggestion to the operating system, which may not be adopted by the operating system. The real order of calls is determined by the thread scheduling algorithm of the operating system.

Java provides a thread scheduler to monitor and control threads in the RUNNABLE state. The scheduling strategy of threads is preemptive, and threads with high priority have a higher chance of priority execution than those with low priority. In the case of the same priority, according to the "first-come-first-served" principle. Every Java program has a default main thread, the first thread launched through JVM, the main thread.

There is another type of thread called the Daemon thread, which has a lower priority by default.

If a thread is a daemon thread, then if all non-daemon threads end, the daemon thread will automatically end.

The application scenario is that when all non-daemon threads end, the rest of the child threads (daemon threads) are automatically closed, eliminating the trouble of continuing to close the child threads.

A thread is a non-daemon thread by default and can be set through the setDaemon (boolean on) of the Thread class.

A thread must exist in a thread group, so what happens when the priority of the thread and the thread group are different? ]

Public static void main (String [] args) {ThreadGroup threadGroup = new ThreadGroup ("T1"); threadGroup.setMaxPriority (6); Thread thread = new Thread (threadGroup, "thread"); thread.setPriority (9); System.out.println ("I am the priority of thread group" + threadGroup.getMaxPriority ()); System.out.println ("I am the priority of thread" + thread.getPriority ());}

Therefore, if the priority of a thread is greater than the maximum priority of the thread group in which the thread belongs, the priority of the thread will be invalidated and replaced by the highest priority of the thread group.

1.3State of Java thread and its main transformation methods

Enum Thread.State

[1] is it feasible to call the start () method of the same thread repeatedly?

[2] if a thread finishes execution (now in the TERMINATED state), is it feasible to call the thread's start () method again?

Check the source code of the start () method in the Thread class, as follows

Public synchronized void start () {/ / threadStatus indicates that the thread in the NEW state if (threadStatus! = 0) throw new IllegalThreadStateException (); / / notifies the thread group of the current thread that this thread is about to start and adds the current thread to the thread group / / reduce the number of unstarted threads in the current thread group group.add (this) Boolean started = false; try {start0 (); started = true;} finally {try {/ / handle threads that failed to start if (! started) {group.threadStartFailed (this) }} catch (Throwable ignore) {} / / the actual startup process of the local method execution thread private native void start0 ()

Inside start (), there is a variable of threadStatus. If it is not equal to 0, calling start () will throw an exception directly.

I made the initial breakpoint inside the start () method, describing what I saw in my breakpoint:

The test code is as follows

@ Test public void testThreadState () {Thread thread = new Thread (()-> {System.out.println ("Thread Run...");}); thread.start (); thread.start ();}

The first thread.start (); is executed as follows

The second thread.start (); is executed as follows

The answer to both questions is not feasible. After calling start () once, the value of threadStatus will change (threadStatus! = 0), and calling the start () method again will throw an IllegalThreadStateException exception.

For example, a threadStatus of 2 means that the current thread state is TERMINATED.

1.4 Communication between Java threads

Thread synchronization is performed between threads in a certain order.

1.4.1 waiting / notification mechanism

The wait / notification mechanism of Java multithreading is based on the wait () method of the Object class and the notify (), notifyAll () method.

The notify () method randomly wakes up a waiting thread, while notifyAll () wakes up all waiting threads.

1.4.2 semaphore

JDK provides a class Semaphore that is similar to the semaphore function. But this article is not to introduce this class, but to introduce a self-implemented semaphore communication based on the volatile keyword.

The volitile keyword ensures memory visibility. If you declare a variable with the volitile keyword and change the value of the variable in one thread, the other threads will immediately see the changed value.

[demand] Let thread 1 output 0, then thread 2 output 1, and then thread An output 2. and so on. How should I achieve it?

Private static Object lock=new Object (); private static volatile int sign=0; static class MyThread1 implements Runnable {@ SneakyThrows @ Override public void run () {while (sign)

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