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 are the three ways to implement multithreaded programming?

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

Share

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

This article mainly explains "what are the three implementation ways of multithreaded programming". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. let's study and learn "what are the three implementation ways of multithreaded programming"?

Understanding of multithreaded programming processes and threads:

Process: a dynamic execution process of a program, which goes through a complete process from code loading, execution to execution, which is the process of process generation, development and final demise.

Multi-process: the operating system can run multiple processes (programs) at the same time, because CPU has a time-sharing mechanism, each process can cycle to get its own CPU time slice; because the execution speed of CPU is very fast, all programs seem to be running at the same time.

The difference and connection between process and thread:

A process is the basic unit of resource scheduling. Running an executable program creates one or more threads, and a process is a running executable program.

Thread is the basic unit of program execution, is a lightweight process, each process has a unique main thread, and there can be only one, the main thread and the process are interdependent, the main thread ends, the process will end.

Specific example (word):

Each startup of Word is equivalent to starting a system process for the operating system, and there are many other programs running on top of this process (spell checking, etc.), so these programs are multi-threaded. If Word is turned off, these spell-checking threads will certainly disappear, but if the spell-checking threads disappear, it will not necessarily make the Word process disappear.

One more word: if you open two word documents, the current operating system has created two processes.

Multithreaded implementation:

Implementing multithreading requires a thread's body class, which can inherit Thread, implement Runnable and complete the definition of the Callable interface.

Thread implements multithreading:

The inheritance structure is as follows:

Public class Thread extends Object implements Runnable

Implement the interface Runnable, so you must implement abstract methods in the interface:

Modifier and TypeMethodDescriptionvoidrun () when an object that implements the interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in a separate thread. Voidstart () causes the thread to start execution; the Java virtual machine calls the thread's run method.

When multiple objects are generated, they execute the code in the run () method concurrently

Although the execution methods of multithreading are defined in the run () method, this method can not be called directly during the actual multithreading startup, because multithreading needs to be executed concurrently, so it needs to be executed through the resource scheduling of the operating system, so the startup of multithreading must be completed by using the start () method in the Thread class. Calling this method will indirectly call the run () method.

Example:

Package Java from entry to project practice. Multithreaded programming. Java multithreaded implementation; class MyThread extends Thread {/ / single inheritance private String title; public MyThread (String title) {this.title = title;} / / override thread's run method @ Override public void run () {for (int I = 0; I)

< 10; i++){ System.out.println(this.title+"运行,i =" +i); } }}public class Main{ public static void main(String[] args){ new MyThread("线程A").start(); //实例化线程对象并启动 new MyThread("线程B").start(); new MyThread("线程C").start(); //对照 /*没有开启多线程*/ new MyThread("线程A").run(); new MyThread("线程B").run(); new MyThread("线程C").run(); }} 由效果图可以看出,三个线程在交替执行:

If the interview questions are:

Why does a thread have to call the start () method when it starts instead of calling the run () method directly?

In this program, after the program calls the start () method inherited from the Thread class, it actually executes the overridden run () method, so why not call run () directly?

To put it simply: because multithreading needs to call operating system resources, there is a key part of the start0 () method under start (), and the navite keyword is defined on the start0 () method.

Public synchronized void start () {if (threadStatus! = 0) throw new IllegalThreadStateException (); group.add (this); boolean started = false; try {start0 (); started = true;} finally {try {if (! started) {group.threadStartFailed (this) }} catch (Throwable ignore) {} private native void start0 (); / / navite

What is navite?

Navite refers to: Java native interface (Java Native Interface) abbreviation: JNI; uses Java to call the functions of the native operating system to complete some special operations

In Java, the body of the start0 () method is given to JVM for implementation, so it will appear in windows or the start0 () implemented in Linux is different, independent of the process, and only cares about the result (whether the function of the local operating system is called)

Start0 () function: let JVM match different operating systems, realize the body of start0 () method, function: realize the call of native function

Specific Baidu, Google bar.

The Runnable API implements multithreading:

The reason: in order to solve the problem of single inheritance in the implementation of multithreading in Thread, and the functional interface has been added.

Modifier and TypeMethodDescriptionvoidrun () when an object that implements the interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in a separate thread.

Implementation code:

Class MyThread implements Runnable {private String title; public MyThread (String title) {this.title = title;} @ Override public void run () {/ / Thread method overrides for (int I = 0; I

< 10;i++){ System.out.println(this.title+"运行,i"+i); } }} 启动方式一: Thread threadA = new Thread(new MyThread("线程A"));Thread threadB = new Thread(new MyThread("线程B"));Thread threadC = new Thread(new MyThread("线程C"));Thread threadD = new Thread(new MyThread("线程D"));Thread threadE = new Thread(new MyThread("线程E"));threadA.start();threadB.start();threadC.start();threadD.start();threadE.start(); 启动方式二: //通过Lambal表达式定义线程主体for(int x = 0; x < 3;x++){ String title = "线程对象-"+x; //实际上Thread传入的类型是Runnable new Thread(()->

{/ / Lambda implements thread body for (int y = 0; y)

< 20; y++){ System.out.println(title+"运行,y"+y); } }).start();} Thread与Runnable的联系: 继承结构: public class Thread extends Object implements Runnable 在之前继承Thread类的时候实际上覆写的还是Runnable接口的run()方法。 实现并发访问资源: package Java从入门到项目实战.多线程编程.Java多线程实现;class MyThreadConcurrent implements Runnable { private int ticket = 5; @Override public void run() { for (int i = 0; i < 100; i++) { //同步操作--》从5-1票数 /*synchronized(this){ if(this.ticket >

0) {System.out.println ("selling tickets, ticket =" + this.ticket--);}} * / / random number of votes if (this.ticket > 0) {System.out.println ("selling tickets, ticket =" + this.ticket--) } public class concurrent resource access {public static void main (String [] args) {MyThreadConcurrent thread = new MyThreadConcurrent (); new Thread (thread) .start (); / / first thread new Thread (thread). Start (); / / second thread new Thread (thread). Start (); / / third thread}}

To sum up: Thread has the limitations of single inheritance and, in some cases, structural irrationality; so subsequent multithreaded implementations use the Runnable interface.

The Callable API implements multithreading:

Why use the Callable interface to implement multithreading?

Because the use of Callable interface implementation makes up for the problem that multithreading of Runnable implementation does not return a value.

The inheritance structure is as follows:

@ FunctionalInterfacepublic interface Callable {public V call () throws Exception {}}

When defining, you can set a generic type, the type of which is the data type returned by the call () method, with the benefit of avoiding the security risks of the downward transformation.

After the thread class body is completed, if you need to start multithreading, you still need to use the Thread class, and because our Callable interface is not related to Thread, we need the FutureTask class to implement the relationship between the two, as shown in the figure:

Through the FutureTask class inheritance structure, we can find that it is a subclass of the Runnable interface.

The code is implemented as follows:

Package Java from entry to project practice. Multithreaded programming .Java multithreaded implementation; import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;class CallableThread implements Callable {@ Override public String call () throws Exception {for (int I = 0; I < 10; iThread +) {System.out.println ("Thread execution x =" + I);} return "xbhog" }} the public class Callable interface implements multithreading {public static void main (String [] args) throws ExecutionException, and InterruptedException {/ / wraps the Callable instantiation in the FutureTask class, so that FutureTask task = new FutureTask (new CallableThread ()) can be associated with the Runnable interface; / / thread starts new Thread (task). Start () / / get the return value System.out.println of call () ("[data returned by thread]:" + task.get ()) }} Thank you for your reading. The above is the content of "what are the three implementation methods of multithreaded programming". After the study of this article, I believe you have a deeper understanding of what the three implementation methods of multithreaded programming are. Specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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