Getting Started with Java threads--defining the Run method in a thread
Source: Internet
Author: User
The Run method is the code that needs to be executed when the thread is run. (You want to use code-that is, the run () method-to describe a process, rather than creating an object that represents the process. There has been a controversy over how to understand threads. It depends on whether you treat the thread as an object or as a process. If you think it is a process, you are free from the oo dogma of everything. But at the same time, if you just want the process to take over a part of the program, you have no reason to make the whole class Runnable. For this reason, it is often a wiser choice to hide the thread code in the form of an inner class. From TIJ3. )
in the Java language, we can implement our run method in the following two ways:
1, overrides the Java.lang.Thread public void Run () method.
public class Simplethread extends Thread {
public Simplethread (String str) {
super (str);
}
public void Run () {
for (int i = 0; i < i++) {
System.out.println (i + "" + getName ());
try {
Sleep ((Long) (Math.random () * 1000));
} catch (Interruptedexception e) {
}
}
System.out.println ("done!" + getName ());
}
}
call the thread defined above:
public class Twothreadsdemo {
public static void Main (string[] args) {
New Simplethread ("Jamaica"). Start ();
New Simplethread ("Fiji"). Start ();
}
}
2, implement Java.lang.Runnable interface:
import Java.awt.Graphics;
import java.util.*;
import Java.text.DateFormat;
import Java.applet.Applet;
public class Clock extends Applet implements Runnable {
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