Java multithreaded Programming in combat

Source: Internet
Author: User
Tags current time sleep thread class

using multithreading in Java programs is much easier than in C or C + +, because the Java programming language provides language-level support. This article demonstrates how intuitive multithreading in Java programs can be through simple programming examples. After reading this article, users should be able to write simple multithreaded programs.

Why do you wait in line?

Here's a simple Java program that completes four unrelated tasks. Such a program has a single control thread that controls the linear movement between these four tasks. In addition, because of the resources required? printers, disks, databases, and displays--because of the inherent latency of hardware and software limitations, each task contains a significant wait time. Therefore, the program must wait for the printer to complete the task of printing the file before accessing the database, and so on. If you are waiting for the program to complete, this is a poor 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 multithreaded models. While we are dealing with certain tasks, we can also allow children, spouses and parents to accomplish other tasks. For example, when I write a letter, I may send my son to the post office to buy stamps. In software terms, this is called multiple control (or execution) threads.

There are two different ways to get multiple control threads:

Multiple processes

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

Thread

Threads are also called lightweight processes (LWP). Because threads can only be active within the scope of a single process, creating a line turndown creates a process that is much cheaper. Thus, threads are preferable to processes because they allow for collaboration and data exchange and are very inexpensive to compute resources. Threads require the support of the operating system, so not all machines provide threads. The Java programming language, as a fairly new language, combines thread support with the language itself, which provides robust support for threads.

Implementing threads using the Java programming language

The Java programming language makes multithreading so simple and effective that some programmers say it's actually natural. Although the use of line turndown in Java is much easier in other languages, there are still some concepts that need to be mastered. One important thing to keep in mind 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 that encapsulates the behavior of a thread. To create a thread, the programmer must create a new class that is exported from the thread class. The programmer must overwrite the Thread's run () function to do useful work. Instead of calling this function directly, you must call the Thread's start () function, which calls run () again. 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 seconds and 3 seconds). This is done by creating two new threads, including a total of three threads in main (). However, because classes that are sometimes run as threads may already be part of a class hierarchy, you cannot create threads by this mechanism. Although you can implement any number of interfaces in the same class, the Java programming language allows only one class to have a parent class. At the same time, some programmers avoid exporting from the Thread class because it imposes a class hierarchy. In this case, you need to runnable the interface.

Runnable interface

This interface has only one function, run (), and this function must be implemented by the class that implements this interface. However, in the case of running this class, the semantics are slightly different from the previous example. We can overwrite the previous example with the Runnable interface. (different parts are shown in bold.) )

Create two new threads without imposing class hierarchies

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 you use the Runnable interface, you cannot create the object of the desired class directly and run it, and you must run it from within an instance of the Thread class. Many programmers prefer the runnable interface because inheritance from the Thread class imposes class hierarchies.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.