Thread class and runnable interface

Source: Internet
Author: User
Tags date now

Thread class and runnable interface

1. inherit the Thread class and reload the run Method

Thread class: this class is used to create threads and perform operations on threads. Thread defines many methods to operate the thread.

The run method of the thread class is empty by default. You can inherit the Thread class and override the run method of the thread class to implement the user thread.

The overall structure is as follows:
Public class mythread extends thread {
Public void run (){
... ...
}
}

Mythread T = new mythread ();
T. Start ();

See example: twothreadstest. Java

Twothreadstest. Java: This example demonstrates how to implement a thread by inheriting the thread method. In this example, two threads are started at the same time. Run the command. Note the running result.
Class twothreadstest {
Public static void main (string ARGs []) {
New simplethread ("Jamaica"). Start ();
New simplethread ("Fiji"). Start ();
}
}

Class simplethread extends thread {
Public simplethread (string Str ){
Super (STR );
}
Public void run (){
For (INT I = 0; I <10; I ++ ){
System. Out. println (I + "" + getname ());
Try {
Sleep (INT) (math. Random () * 1000 ));
} Catch (interruptedexception e ){}
}
System. Out. println ("done! "+ Getname ());
}
}

In this example, the main () method of the twothreadstest class constructs two simplethread classes, one called "Jamaica" and the other named "Fiji ", the START () method is called immediately after the construction to start the two threads.
Simplethread is a subclass of thread. It first defines a constructor. The independent variable is of the string type. For example, the preceding "Fiji" indicates the thread name. The second method in the simplethread class is the run () method, which overwrites the run () method in the Thread class. The run () method is a ten-time loop. The number of cycles and the name of the currently running thread are displayed in each loop, and then a random interval is sleep. After the loop ends, "done!" is displayed! "And thread name.

Let's take a look at the running results:

0 Jamaica
0 Fiji
1 Fiji
1 Jamaica
2 Jamaica
2 Fiji
3 Fiji
3 Jamaica
4 Jamaica
4 Fiji
5 JAMAICA
5 Fiji
6 Fiji
6 Jamaica
7. Jamaica
7 Fiji
8 Fiji
9 Fiji
8 Jamaica
Done! Fiji
9 Jamaica
Done! Jamaica

We can see that in the output result, the names of the two threads are mixed and there is no order to follow, because the two threads run simultaneously and both display the output simultaneously.

 

2. Execute the runnable interface class to implement the run Method

Create a thread by creating an object that implements the runnable interface and using it as the target object of the thread.

Runnable interface: defines an abstract method run (). Definition:

Public interface java. Lang. runnable {
Public abstract void run ();
}

The overall framework is as follows:

Class myrunner implements runnable {
Public void run (){
...
}
}

Myrunner r = new myrunner ();

Thread t = new thread (threadgroup group, runnable target, string name );

See example:

Threadtesterer. Java
Threadtest. Java

For example:

Public class clock extends java. Applet. Applet
Implements runnable {
Thread clockthread;
Public void start (){
If (clockthread = NULL ){
Clockthread = new thread (this, "Clock ");
Clockthread. Start ();
}
}
Public void run (){
While (clockthread! = NULL ){
Repaint ();
Try {
Clockthread. Sleep (1000 );
} Catch (interruptedexception e ){
}
}
}
Public void paint (Graphics g ){
Date Now = new date ();
G. drawstring (now. gethours () + ":"
+ Now. getminutes () + ":"
+ Now. getseconds (), 5, 10 );
}
Public void stop (){
Clockthread. Stop ();
Clockthread = NULL;
}
}

This is a clock applet that displays the current time and updates every second. The applet uses the runnable interface to provide the run () method for its thread. The class clock is extended by the class applet, but it also requires a thread to update and display the time. Java does not support multiple inheritance, so it cannot inherit the Thread class, but uses the runnable interface.
First, a thread named clockthread is constructed in the START () method and the thread. Start () method is called to start the thread. That is, the system thread relationship is established during Java runtime. The following statement creates a new thread:

Clockthread = new thread (this, "Clock ");

This is the first independent variable in the thread constructor. As the target object of the thread, it must implement the runnable interface. In this constructor, the thread clockthread uses the run () method in its runable target object as its run () method. In this example, the target object is the clock applet. The second variable in the constructor is the thread name.

After the thread is started, call the run () method of the target object unless the thread is stopped. In the loop of the run () method, the applet redraws itself and then sleeps for 1 second. At the same time, it needs to capture and process exceptional events.

If you leave the page showing the clock, the application will call the stop () method to leave the thread empty. When you return, a new thread is created.

In a specific application, the method used to construct the thread body depends on the situation. Generally, when a thread has inherited another class, it should be constructed using the second method to implement the runnable interface.

3. Summary:

1. Both methods need to execute the thread's start method to allocate required system resources to the thread, schedule the thread to run and execute the thread's run method.

2. In a specific application, the method used to construct the thread body depends on the situation. Generally, when a thread has inherited another class, it should be constructed using the second method to implement the runnable interface.

3. It is not recommended to call a stop () command to terminate a thread. Instead, let the run () method end naturally.

See example: threadcontroller. Java

 

Close

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.