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 Multithreading in Java Program

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the Java program multithreading example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

Why are you waiting in line?

The following simple Java program performs four unrelated tasks. Such a program has a single thread of control that moves linearly between these four tasks. Besides, because of the resources required? Printers, disks, databases, and displays-due to hardware and software limitations, each task contains significant latency. Therefore, the program must wait for the printer to complete the task of printing files before accessing the database, and so on. If you are waiting for the program to complete, this is a botched use of computing resources and your time. One way to improve this program is to make it multithreaded.

Four unrelated tasks

Class myclass {

Static public void main (String args []) {

Print_a_file ()

Manipulate_another_file ()

Access_database ()

Draw_picture_on_screen ()

}

}

In this case, each task must wait for the previous task to complete before starting, even if the task involved is irrelevant. However, in real life, we often use the multithreaded model. While we deal with certain tasks, we can also let our children, spouses and parents complete other tasks. For example, I might send my son to the post office to buy stamps while writing a letter. In software terms, this is called multiple control (or execution) threads.

Multiple control threads can be obtained in two different ways:

1. Multiple processes

Multiple processes can be created in most operating systems. When a program starts, it creates a process for each task that is about to start and allows them to run at the same time. When one program is blocked waiting for network access or user input, another program can run, which increases resource utilization. However, creating each process in this way comes at a price: setting up a process takes up a significant portion of processor time and memory resources. Moreover, most operating systems do not allow processes to access the memory space of other processes. As a result, communication between processes is inconvenient and does not provide itself to an easy programming model.

2. Thread

Threads are also called lightweight processes (LWP). Because threads can only be active within the scope of a single process, creating a thread is much cheaper than creating a process. In this way, threads are preferable to processes because they allow collaboration and data exchange, and are very cheap in terms of computing resources. Threads need the support of the operating system, so not all machines provide threads. The Java programming language, as a fairly new language, has combined thread support with the language itself, thus providing robust support for threads.

Using Java programming language to implement threads

The Java programming language makes multithreading so simple and efficient that some programmers say it is actually natural. Although it is much easier to use threads in Java than in other languages, there are still some concepts to master. One important thing to remember is that the main () function is also a thread and can be used to do useful work. Programmers need to create new threads only if they need multiple threads. Thread class

The Thread class is a concrete class, that is, not an abstract class, which encapsulates the behavior of threads. To create a thread, the programmer must create a new class derived from the Thread class. Programmers must override the run () function of Thread to do useful work. The user does not call this function directly; instead, the user must call the start () function of Thread, which then calls run (). The following code illustrates its use:

Create two new threads

Import java.util.*

Class TimePrinter extends Thread {

Int pauseTime

String name

Public TimePrinter (int x, String n) {

PauseTime = x

Name = n

}

Public void run () {

While (true) {

Try {

System.out.println (name + ":" + new

Date (System.currentTimeMillis ())

Thread.sleep (pauseTime)

} catch (Exception e) {

System.out.println (e)

}

}

}

Static public void main (String args []) {

TimePrinter tp1 = new TimePrinter (1000, "Fast Guy")

Tp1.start ()

TimePrinter tp2 = new TimePrinter (3000, "Slow Guy")

Tp2.start ()

}

}

In this example, we can see a simple program that displays the current time on the screen at two different intervals (1 second and 3 seconds). This is done by creating two new threads, including three for main (). However, because sometimes a class to run as a thread may already be part of a class hierarchy, threads can no longer be created according to this mechanism. Although any number of interfaces can be implemented in the same class, the Java programming language allows only one parent class for a class. At the same time, some programmers avoid exporting from the Thread class because it imposes a class hierarchy. In this case, the runnable interface is required.

Runnable interface

There is only one function for this interface, run (), which must be implemented by a class that implements this interface. However, when it comes to running this class, the semantics are slightly different from the previous example. We can overwrite the previous example with the runnable interface. The different parts are represented in boldface. )

Create two new threads without imposing a class hierarchy

Import java.util.*

Class TimePrinter implements Runnable {

Int pauseTime

String name

Public TimePrinter (int x, String n) {

PauseTime = x

Name = n

}

Public void run () {

While (true) {

Try {

System.out.println (name + ":" + new

Date (System.currentTimeMillis ())

Thread.sleep (pauseTime)

} catch (Exception e) {

System.out.println (e)

}

}

}

Static public void main (String args []) {

Thread T1 = new Thread (new TimePrinter (1000, "Fast Guy"))

T1.start ()

Thread T2 = new Thread (new TimePrinter (3000, "Slow Guy"))

T2.start ()

}

}

Note that when using the runnable interface, you cannot directly create an object of the desired class and run it; you must run it from within an instance of the Thread class. Many programmers prefer the runnable interface because inheriting from the Thread class imposes a class hierarchy.

Thank you for reading this article carefully. I hope the article "sample Analysis of Multi-threading in Java programs" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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