Multi-threaded Implementation---implement Runnable interface

Source: Internet
Author: User
Tags repetition

Multi-threaded Implementation---implement Runnable interface

A class can also be implemented by implementing the Java.lang.Runnable interface if it needs to be capable of multithreading. According to the syntax of the Java language, a class can implement any number of interfaces, so the implementation of this way in the actual implementation of the commonality is better than the way described earlier.

The sample code to implement multithreading using the implement Runnable interface is as follows:

/**

* Test class

*/

public class Test2 {

public static void Main (string[] args) {

Creating objects

Myrunnable Mr = New Myrunnable ();

Thread t = new thread (MR);

Start

T.start ();

try{

for (int i = 0;i < 10;i++) {

Thread.Sleep (1000);

System.out.println ("main:" + i);

}

}catch (Exception e) {}

}

}

/**

* Multithreading with implementation of the Runnable interface

*/

public class Myrunnable implements Runnable {

public void Run () {

try{

for (int i = 0;i < 10;i++) {

Thread.Sleep (1000);

System.out.println ("Run:" + i);

}

}catch (Exception e) {}

}

}

The sample code implements the same functionality as the previous implementation. When implemented using this approach, it is necessary to implement a multithreaded class implementation runnable, which requires overriding the Run method, and then writing code that needs to be executed in multithreaded form inside the run method or inside the Run method.

Where you need to start a thread, first create an object of type myrunnable, then create an object of the thread class based on that object, and finally call the start method of the thread object to start the thread. The code is as follows:

Creating objects

Myrunnable Mr = New Myrunnable ();

Thread t = new thread (MR);

Start

T.start ();

In this approach, most are similar to those described earlier, and the code that starts up is a little more cumbersome. This approach is also a primary way to implement threading.

12.2.3 using the timer and timertask combination

The last way to implement multithreading is to use the timer and TimerTask class in the Java.util package to implement multi-threading, which is also a convenient way to implement threads.

In this implementation, the timer class implements a function like the alarm clock, which is to trigger a thread at regular intervals or at a certain time. In fact, the timer class itself implements a thread, but this thread is used to implement calls to other threads. The TimerTask class is an abstract class that implements the Runnable interface, so the class has the ability to multithreading, as described earlier.

In this implementation, by inheriting TimerTask, this class gets the ability to multithreading, writing code that requires multi-threaded execution inside the Run method, and then starting the execution of the thread through the Timer class.

In practice, a timer can start a thread of any number of TimerTask implementations, but there is a blockage between multiple threads. So if you need to run completely independently between multiple threads, it's best to start a timertask implementation with a timer.

The multithreaded sample code implemented using this implementation is as follows:

Import java.util.*;

/**

* Test class

*/

public class Test3 {

public static void Main (string[] args) {

Create a Timer

Timer T = new timer ();

Create TimerTask

Mytimertask mtt1 = new Mytimertask ("Thread 1:");

Start thread

T.schedule (mtt1, 0);

}

}

Import Java.util.TimerTask;

/**

* Multithreading is implemented in a way that inherits the TimerTask class

*/

public class Mytimertask extends TimerTask {

String s;

Public Mytimertask (String s) {

THIS.S = s;

}

public void Run () {

try{

for (int i = 0;i < 10;i++) {

Thread.Sleep (1000);

SYSTEM.OUT.PRINTLN (s + i);

}

}catch (Exception e) {}

}

}

In this example, the Mytimertask class implements multithreading, and code executed in multithreaded form is inside the run method of the class, and the functionality of the class is similar to the previous multithreaded code implementation.

In this code, when you start a thread, you need to first create an object of the timer class, and a Mytimertask thread class, and then use the schedule method of the timer object to implement the code for the startup thread:

Create a Timer

Timer T = new timer ();

Create TimerTask

Mytimertask mtt1 = new Mytimertask ("Thread 1:");

Start thread

T.schedule (mtt1, 0);

The first parameter in the Schedule method MTT1 represents the thread object that needs to be started, and the second parameter 0 represents a delay of 0 milliseconds to start the thread, which is to start immediately.

Because the schedule method is more important, the following is a detailed description of the timer class of the four schedule methods:

1. public void Schedule (TimerTask task,date time)

The function of this method is to execute a thread task when it reaches the time specified or has exceeded that time. For example, if T is a Timer object, the task is a TimerTask thread object that needs to be started, and subsequent examples are implemented with this Convention, the sample code for the boot thread is as follows:

Date d = new Date (2009-1900,10-1,1,10,0,0);

T. Schedule (TASK,D);

The purpose of the sample code is to start the thread task when the time reaches the time specified by D or beyond that time (for example, October 2, 2009).

2. public void Schedule (timertask task, Date Firsttime, long period)

The function of this method is to start a task-specific thread every period milliseconds, starting at the time it reaches Firsttime. The sample code is as follows:

Date d = new Date (2009-1900,10-1,1,10,0,0);

T. Schedule (task,d,20000);

The purpose of this sample code is to start a thread task every 20000 milliseconds after the time has elapsed or exceeds the time specified by D, which repeatedly triggers the thread.

3. public void Schedule (TimerTask task,long delay)

This method is similar to the first method, which is to start a thread task after the schedule method has been executed for delay milliseconds. The sample code is as follows:

T. Schedule (task,1000);

The purpose of the sample code is to start a thread task after 1000 milliseconds of executing the line's startup code.

4. public void Schedule (TimerTask task,long Delay,long period)

This method is similar to the second method, which is to start the thread task after the schedule method is executed after delay milliseconds, and then repeatedly start the thread task every period milliseconds.

The exception to note is that the start thread in the Timer class also contains two scheduleatfixedrate methods whose parameters are consistent with the second and fourth above, which is the exact delay when the thread is repeatedly started. For the schedule method, if the repetition interval is 1000 milliseconds, the actual delay time is 1000 milliseconds plus the time that is consumed by the system execution, for example, 5 milliseconds, the actual time interval for each round is 1005 milliseconds. For the Scheduleatfixedrate method, if the set repetition interval is 1000 milliseconds and the system executes at a time of 5 milliseconds, the delay becomes 995 milliseconds, guaranteeing 1000 milliseconds per round interval.

After introducing the schedule method, let's take a look at the previous example code, if you start two mytimertask threads in the test class, one of the implementation code is:

Import Java.util.Timer;

/**

* Test class

*/

public class Test4 {

public static void Main (string[] args) {

Create a Timer

Timer T = new timer ();

Create TimerTask

Mytimertask mtt1 = new Mytimertask ("Thread 1:");

Mytimertask mtt2 = new Mytimertask ("Thread 2:");

Start thread

System.out.println ("Start start");

T.schedule (MTT1, 1000);

System.out.println ("Start thread 1");

T.schedule (MTT2, 1000);

System.out.println ("Start thread 2");

}

}

In this sample code, a Timer object T is used to start the object Mtt1 and Mtt2 of the two mytimertask types in turn. The result of the execution of the program is:

Start start

Start thread 1

Start Thread 2

Thread 1:0

Thread 1:1

Thread 1:2

Thread 1:3

Thread 1:4

Thread 1:5

Thread 1:6

Thread 1:7

Thread 1:8

Thread 1:9

Thread 2:0

Thread 2:1

Thread 2:2

Thread 2:3

Thread 2:4

Thread 2:5

Thread 2:6

Thread 2:7

Thread 2:8

Thread 2:9

As can be seen from the execution results of the program, in the Test4 class Mtt1 and Mtt2 are started, as described in the previous schedule method, the two threads will be executed after 1000 milliseconds of thread initiation. However, it can be seen from the actual execution effect that these two threads are not executed concurrently, but are executed in turn, mainly because there is an impact between multiple timertask that a timer initiates, and when the previous thread does not complete, it blocks subsequent thread execution. So thread 2 gets executed when thread 1 finishes executing.

If thread 1 and thread 2 are required for simultaneous execution, you only need to start the timertask thread with two timer respectively, starting with the sample code as follows:

Import Java.util.Timer;

/**

* Test class

*/

public class Test5 {

public static void Main (string[] args) {

Create a Timer

Timer T1 = new timer ();

Timer t2 = new timer ();

Create TimerTask

Mytimertask mtt1 = new Mytimertask ("Thread 1:");

Mytimertask mtt2 = new Mytimertask ("Thread 2:");

Start thread

System.out.println ("Start start");

T1.schedule (MTT1, 1000);

System.out.println ("Start thread 1");

T2.schedule (MTT2, 1000);

System.out.println ("Start thread 2");

}

}

In this example, two timer objects, T1 and T2, are used to start the two TimerTask thread objects mtt1 and MTT2, which do not interfere with each other, thus achieving the purpose of simultaneous execution.

When running with the above example, since the timer itself thread is not finished, the program is not finished after the program output is completed, and the execution of the program needs to be terminated manually. For example, in Eclipse, you can click the Red "teminate" button above the console to end the program.

12.2.4 Summary

There are three ways to implement threads, so that's a simple introduction. In fact, regardless of the implementation of the way, can implement multi-threading, in the premise that the syntax allows, can be implemented in any way. In comparison, the implementation of the Runnable interface is a common way.

Just from the syntax of the implementation of the thread, or can not realize the mystery of thread implementation, the following will be a few simple examples to realize the power of threading, and realize the magic of concurrent programming, so that can enter the field of concurrent programming to play the advantages of technology.

Multi-threaded Implementation---implement Runnable interface

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.