Multi-threaded
1.1 Creating a thread class
In Java, you can simply inherit the creation of your own thread class from the THREAD class:
Public class myfirstthread extends thread {
Public void run () {.
}
Description:
(1) The Thread class is in the java.lang package, so you don't have to display import;
(2) It is best to override the Run () method to run the required code from the THREAD class.
You can instantiate and run the thread as follows:
Myfirstthread Amft = new myfirstthread ();
AMFT.START ();
Description:
(3) After instanting the thread class, the system will initialize some parameters, mainly to create a name for threads, add new threads to the specified thread group, initialize the memory space required to run, specify the new thread priority, specify its Swinging thread;
(4) The Start method is the method in the Thread class, which calls the RUN method, runs the specified code in the new thread;
(5) In addition to the START method, the classes from Thread also have some other major methods: STOP, SUSPEND, RESUME, etc .;
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 Ourslf!
8: }
9:
10: public void run () {
11: While (true) {
12: system.out.println (thread.currentthread (). Getname ());
13: Try {
14: thread.sleep (delay);
15:} 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 multi-thread run specified code is that this interface when creating a class: public class mysecondthread extends importantclass implements runnable {
Public void run () {.
}
Description:
(1) This type of implementing runable interface, indicating that intention to run in a separate thread, THREAD is also the import runable interface;
(2) The Implement Runalbe interface requires at least the RUN method;
The following is an example of creating a new thread to run the class:
Mysecondthread amst = new mysecondthread ();
Thread Athread = New Thread (AMST);
Athread.start ();
Description:
(3) Thread class has multiple constructor thread (), thread (Runable Target), etc., this example is the second constructor, which has a runable function, so instances to run in multithreading The class must be Implement Runable;
(4) ATHEAD.START () method calls the TARGET.RUN method in the Thread instance, this example is the RUN method in the MysecondThread instance;
(5) The Thread constructor can also specify the thread name, run the desired STACK, the group belongs to the group, etc .;
In order to prevent the thread from being abnormal, it is necessary to put the start method into Try ... Catch, such as:
Try {
mythread.start ();
} catch (threadDeath ATD) {
System.out.println ("End Thread");
Throw atd;
}
In this example, the THREADDEATH is abnormal, and the abnormality is re-thus processed, so that Java executes the STOP method to clean up the resources.
1.3 Priority of thread
The execution of multiple threads has a certain priority, for the following example:
Public class runnablepotato imports runnable {
Public void run () {
While (True)
System.out.println (thread.currentthread (). Getname ());
}
Public class pootothreadtester {
Public static void main (String Argv []) {
Runnablepotato ARP = New Runnablepotato ();
Thread T1 = New Thread (ARP, "One Potato");
Thread T2 = New Thread (ARP, "Two Potato");
T1.Start ();
T2.Start ();
}
For non-seizuated systems, the first thread in the above example will run, and the second thread does not have the opportunity to run; for the preemptive system, the two-person thread will run alternately.
In order to make multi-threads run in non-seizening, it is best to add the following statement in the RUN method:
Thread.yield ()
which is
Public void run () {
While (True)
System.out.println (thread.currentthread (). GetName ()); thread.yield ()
}
Thread.yield will temporarily let other threads have the opportunity to run for a short period of time. After this period, the thread is inherited. The above functions can also be implemented with the thread.sleep () method.
There is a priority level in Java from 1 to 10, where 1 can be represented by thread.min_Priority, 5 can be used with thread.Norm_Priority, 10 can be represented by thread.max_priority, newly built a thread default level is thread.norm_priority. You can also change the priority level of the thread using the setPriority method, such as T1.SETPRIORITY (T2.GetPriority 1).
In contrast to the Yield method, it is a Join method, which indicates that the designated thread is running, such as:
Try {t.join ();} catch (interruptedexception ignored) {}
Refers to the next step by means that the thread T is running. This is relatively rare.
1.4 synchronized
In order to ensure a method or an object can only be accessed by one method, then you need to use the synchronized keyword.
Such as:
Public synchronized void countme () {
CRUCIALVALUE = 1;
}
The operation in this method is a atomic operation, = To perform three steps, after using Synchronized, these three steps are atomic, that is, before the three steps are completed, other access to CRUCIALVALUE will be Refused, you can guarantee COUNTME thread security.
another example:
SYNCHRONIZED (P) {
Safex = p.x ();
Safey = p.y ();
}
Indicates that the P object is locked within the block range, which is not allowed to modify the value in the P object.
The role of the above code is to protect variables within an object cannot be accessed by multiple threads simultaneously. Here, how to protect Class Variable thread security:
Public class staticcounter {
Private static int crucialue;
Public void countme () {
Synchronized (getClass ()) {
CRUCIALVALUE = 1;
}}}
Description:
(1) In this example, CrucialValue is private and static, which means that it can be accessed by all instances of the class;
(2) Synchronized uses the getClass method to get the class name without using StaticCounter directly.
(3) If crucialvalue is public, then modify the code:
Synchronized (Class.Forname ("staticcouname)) {
StaticCounter.CrucialValue = 1;
}