One of the simplest ways to write thread-based code: to derive a Thread class
Source: Internet
Author: User
One of the simplest ways to write thread-based code: the derived Thread class-general Linux technology-Linux programming and kernel information. For more information, see the following. Derived Thread class
One of the simplest ways to write Thread-based code is to derive the java. lang. Thread class. This thread class is a member of the java. lang package. By default, the thread class can be called by all Java applications. To use The Thread class, we need to understand The five methods defined in The java. lang. Thread class:
Run (): This method is used for thread execution. You need to reload this method so that the thread can do specific work.
Start (): This method enables the thread to start run ().
Stop (): This method is opposite to the start method. It stops the running of the thread.
Suspend (): Unlike the stop method, this method does not terminate unfinished threads. It only suspends threads and can be recovered later.
Resume (): This method restarts a suspended thread.
Run the program in List A. For the running result, see List B.
List A: Extended Thread class
Class TestThreads {
Public static void main (String args []) {
Class MyThread extends Thread {
String which;
MyThread (String which ){
This. which = which;
}
Public void run (){
Int iterations = (int) (Math. random () * 100) % 15;
Int sleepinterval = (int) (Math. random () * 1000 );
List A demonstrates how to generate A new class from the existing Thread class. The newly created class reloads the run method. Interestingly, you do not need to strictly implement the run method, because the Thread class provides a default run method, although it is not particularly useful.
In some cases, we cannot simply change the parent class of the specified object. We still need to use threads. In this case, we need to use the Runnable interface.
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.