J2se review notes 2-Thread

Source: Internet
Author: User

 

Thread. currentthread (). isinterrupted () // check whether the current process is in a non-interrupted state

A process is a static concept. Generally speaking, the execution of a process refers to the execution of the main thread in the process. In our machine, the actual execution is a thread.

 

 

1. multi-thread example for implementing the runnable interface /**
* Class for implementing the runnable interface
*
* @ Author leizhimin 18:12:10
*/
Public class dosomething implements runnable {
Private string name;

Public dosomething (string name ){
This. Name = Name;
}

Public void run () {
for (INT I = 0; I <5; I ++) {
for (long K = 0; k <100000000; k ++);
system. out. println (name + ":" + I );
}< BR >}/ **
* test the multithreading implemented by the runnable class Program
*
* @ author leizhimin 18:15:02
*/
public class testrunnable {
Public static void main (string [] ARGs) {
dosomething ds1 = new dosomething ("A 3");
dosomething ds2 = new dosomething ("Li 4");

Thread T1 = new thread (ds1 );
Thread t2 = new thread (DS2 );

T1.start ();
T2.start ();
}
} Execution result: Li Si: 0
A: 0
Li Si: 1
A 3: 1
Li Si: 2
Li Si: 3
A 3: 2
Li Si: 4
A 3: 3
A 3: 4

Process finished with exit code 0

2. multi-threaded example of extension Thread class implementation /**
* Multi-thread program for extension of Thread class
*
* @ Author leizhimin 18:22:13
*/
Public class testthread extends thread {
Public testthread (string name ){
Super (name );
}

Public void run (){
For (INT I = 0; I <5; I ++ ){
For (long K = 0; k <100000000; k ++ );
System. Out. println (this. getname () + ":" + I );
}
}

Public static void main (string [] ARGs ){
Thread T1 = new testthread ("A 3 ");
Thread t2 = new testthread ("Li Si ");
T1.start ();
T2.start ();
}
} Execution result: a 3: 0
Li Si: 0
A 3: 1
Li Si: 1
A 3: 2
Li Si: 2
A 3: 3
A 3: 4
Li Si: 3
Li Si: 4

Process finished with exit code 0

 

 

 

 

The state conversion of a thread is the basis of thread control. The total thread status can be divided into five major states: active, dead, runable, running, waiting/blocking. Use a diagram to describe it as follows:

 

1. New State: the thread object has been created and the START () method has not been called on it. 2. Running status: When the thread is ready, it enters the status of waiting in queue for the CPU to allocate time slice. When the START () method is called, the thread first enters the runable state. After the thread is running or after it is returned from the blocking, waiting, or sleep status, it also returns to the runable status. 3. Running status: the CPU selects a thread from the waiting thread as the status of the current thread. This is the only way for a thread to enter the running state. 4. Waiting/blocking/sleep status: this is the status where the thread is eligible to run. In fact, the three States are combined into one. The common feature is that the thread is still active, but there are currently no conditions to run. In other words, it is runable, but if an event appears, it may return to the runable status. 5. Dead state: When the thread's run () method is completed, it is considered dead. This thread object may be active, but it is no longer a separate thread. Once a thread dies, it cannot be resumed. If the START () method is called on a dead thread, a java. Lang. illegalthreadstateexception is thrown.

 

 

 

Java thread: Thread Scheduling-sleep

 

The thread sleep is one of the simplest ways to make the thread out of the CPU. When the thread sleep, the CPU resources are handed over to other threads so that the thread can be rotated for execution. When the thread sleep for a certain period of time, the thread will wake up and enter the preparation status to wait for execution. The thread automatically wakes up when its sleep ends and returns to the running status, not the running status. The time specified in sleep () is the shortest time that the thread does not run. Therefore, the sleep () method cannot guarantee that the thread starts to run after its sleep expires. The thread sleep methods are thread. Sleep (long millis) and thread. Sleep (long millis, int Nanos). They are static methods. Which thread does the Sleep call? Simply put, the thread that calls sleep will sleep. Java thread: Thread Scheduling-concession the concession meaning of the thread is to let the currently running thread out of CPU resources, but who does not know, just let out, the thread status back to the runable status. Thread concession uses the thread. Yield () method, and yield () is a static method. The function is to pause the currently executed thread object and execute other threads. Java thread: the meaning of Thread Scheduling-merge thread merging is to merge the threads of several parallel threads into a single thread for execution, in the Application scenario, the join method can be used when a thread must wait for another thread to complete execution. **  
* Java thread: Thread Scheduling - Merge
*  
* @ Author leizhimin 2009 - 11 - 4   9 : 02 : 40  
*/  
Public   Class Test {
Public   Static   Void Main (string [] ARGs ){
Thread T1 =   New Mythread1 ();
T1.start ();

For ( Int I =   0 ; I <   20 ; I ++ ){
System. Out. println ( " Main Thread No. "   + I +   " Second execution! " );
If (I >   2 ) Try {
// When the T1 thread is merged into the main thread, the main thread stops the execution and executes the T1 thread until the T1 thread continues after execution.
T1.join ();
} Catch (Interruptedexception e ){
E. printstacktrace ();
}
}
}
}

Class Mythread1 Extends Thread {
Public   Void Run (){
For ( Int I =   0 ; I <   10 ; I ++ ){
System. Out. println ( " Thread 1 "   + I +   " Second execution! " );
}
}
}

 

 

The main thread executes 0th times!
The main thread executes 1st times!
The main thread executes 2nd times!
Thread 1 executes 0th times!
The main thread executes 3rd Times!
Thread 1 executes 1st times!
Thread 1 executes 2nd times!
Thread 1 executes 3rd Times!
Thread 1 executes 4th times!
Thread 1 executes 5th times!
Thread 1 executes 6th times!
Thread 1 executes 7th times!
Thread 1 executes 8th times!
Thread 1 executes 9th times!
The main thread executes 4th times!
The main thread executes 5th times!
The main thread executes 6th times!
The main thread executes 7th times!
The main thread executes 8th times!
The main thread executes 9th times!
The main thread executes 10th times!
The main thread executes 11th times!
The main thread executes 12th times!
The main thread executes 13th times!
The main thread executes 14th times!
The main thread executes 15th times!
The main thread executes 16th times!
The main thread executes 17th times!
The main thread executes 18th times!
The main thread executes 19th times!

 

 

At the current position, we have introduced three methods for the thread to exit the running status: 1. Call the thread. sleep (): the minimum number of milliseconds to sleep the current thread (although it may be interrupted before the specified time ). 2. Call thread. Yield (): too many things cannot be guaranteed, although it usually returns the current running thread to the runability state, so that threads with the same priority have the opportunity to execute. 3. Call the join () method to ensure that the execution of the current thread is stopped until the threads added to the thread are completed. However, if the thread it joins does not survive, the current thread does not need to be stopped. 4. When the run () method of the thread is completed. The thread will also leave the running state. Java thread: synchronization of threads-synchronization method thread synchronization is a means to ensure safe access to competing resources by multithreading.

 

Public   Class Testsync Implements Runnable
{
Timer = New Timer ();
  Public   Static   Void Main (string [] ARGs)
{
Testsync Test = New Testsync ();
// Here, the two threads pass in the same object test, and the test object contains the same timer object;
Thread T1 = New Thread (test );
Thread T2 = New Thread (test );
T1.setname ( " T1 " );
T2.setname ( " T2 " );
T1.start ();
T2.start ();

}
Public   Void Run
{
Timer. Add (thread. currentthread (). getname ());
}
}
Class Timer
{
  Private   Static   Int Num = 0 ;
  Public   Void Add (string name)
{
  Synchronized ( This )
{
Num ++ ;
Try {Thread. Sleep ( 1 );}
Catch (Interruptedexception e ){}
System. Out. println (name + " You are the first " + Num + " Timer threads " );
}
}

}

 

 

When using the synchronized keyword, try to avoid using the sleep or yield method in the synchronized method or synchronized block, because the synchronized block occupies the object lock, when you rest, other threads can only be executed after you wake up. It not only seriously affects efficiency, but also is not logical.

 

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.