Java multi-thread programming practices

Source: Internet
Author: User

Java multi-thread programming practices

Multithreading in Java programs is much easier to use than C or C ++, because the Java programming language provides language-level support. This article uses simple programming examples to illustrate how intuitive multithreading is in Java programs. After reading this article, you should be able to write simple multi-threaded programs.

Why wait in queue?

The following simple Java program completes four unrelated tasks. Such a program has a single control thread that controls linear movement between the four tasks. In addition, because of the required resources? Printers, disks, databases, and displays-each task contains a significant wait time due to hardware and software limitations. Therefore, the program must wait for the printer to complete the task of printing files before accessing the database. If you are waiting for the completion of the program, this is a poor use of computing resources and your time. One way to improve this program is to make it multi-threaded.

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 example, each task must wait for the previous task to complete before it starts, even if the involved task is irrelevant. However, in real life, we often use multi-threaded models. While dealing with some tasks, we can also let our children, spouse, and parents complete other tasks. For example, when I write a letter, I may send my son to the post office to buy stamps. In terms of software, this is called multiple control (or execution) threads.

You can use two different methods to obtain 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 to be started and allow them to run simultaneously. When a program is blocked because it is waiting for network access or user input, another program can run, which increases resource utilization. However, creating a process in this way requires a certain cost: setting a process takes a considerable amount of CPU time and memory resources. In addition, most operating systems do not allow processes to access the memory space of other processes. Therefore, inter-process communication is inconvenient and does not provide it to easy programming models.

Thread

A thread is also called a Lightweight Process (LWP ). Because threads can only be active within the scope of a single process, it is much cheaper to create a thread than to create a process. In this way, because threads allow collaboration and data exchange, and are very cheap in computing resources, threads are more desirable than processes. Threads must be supported by the operating system, so not all machines provide threads. Java programming language, as a new language, has integrated thread support with the language itself, which provides strong support for threads.

Use Java programming language to implement threads

Java programming languages make multithreading so simple and effective 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 that need to be mastered. One important thing to remember is that the main () function is also a thread and can be used for useful work. A programmer must create a new thread only when multiple threads are required.

Thread class

The Thread class is a specific class, that is, it is not an abstract class, which encapsulates the Thread behavior. To create a Thread, the programmer must create a new class to export 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 start () function of Thread and then call run (). The following code illustrates its usage:

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 time intervals (1 second and 3 seconds. This is done by creating two new threads, including three main () threads. However, because sometimes the class to run as a thread may already be part of a class hierarchy, you cannot create a thread using this mechanism. Although you can implement any number of interfaces in the same class, Java programming language only allows 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, the runnable interface is required.

Runnable interface

This interface has only one function, run (), which must be implemented by the class that implements this interface. However, when running this class, its semantics is slightly different from the previous example. We can use the runnable interface to rewrite the previous example. (Different parts are expressed in black .)

Create two new threads without imposing class Layers

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 directly create the object of the required class and run it. You must run it from an instance of the Thread class. Many programmers prefer the runnable interface, because inheritance from the Thread class imposes class levels.

Related Article

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.