1. Multithreading
1.1 Creating a thread class
In Java, you can simply inherit from the thread class to create your own threading class:
public class Myfirstthread extends Thread {
public void Run () {...}
}
Description
(1) The thread class bit is Java.lang package, so you can not display import;
(2) classes inherited from the thread class are best overloaded with the run () method to run the required code;
You can instantiate and run the thread in the following ways:
Myfirstthread amft = new Myfirstthread ();
Amft.start ();
Description
(3) After instantiating the thread class, the system initializes some parameters, mainly creating a name for the thread, adding a new thread to the specified thread group, initializing the memory space required for the thread to run, specifying the priority level of the new thread, and specifying its waiting thread;
(4) The Start method is a method in the thread class that invokes the Run method and runs the specified code in a new thread;
(5) In addition to the Start method, the classes inherited from thread also have some other main methods: Stop,suspend,resume;
The following is a complete thread-derived class:
1:public class Complexthread extends Thread {
2:private int delay;
3:
4:complexthread (String name, float seconds) {
5:super (name);
6:delay = (int) seconds * 1000; Delays are in milliseconds
7:start (); Start Up ourself!
8:}
9:
10:public void Run () {
11:while (True) {
12:system.out.println (Thread.CurrentThread (). GetName ());
13:try {
14:thread.sleep (delay);
:} catch (Interruptedexception e) {
16:return;
17:}
18:}
19:}
20:
21:public static void Main (String argv[]) {
22:new complexthread ("One Potato", 1.1F);
23:new complexthread ("Two potato", 1.3F);
24:new complexthread ("Three potato", 0.5F);
25:new Complexthread ("Four", 0.7F);
26:}
27:}
1.2 Runable interface
Another way to create a multithreaded run of the specified code is to implement runable this interface when the class is created:
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