thread (i)a thread is defined in the composition:
1. Create Tasks and Threads:
1 New Taskthread (); Create task 2 thread taskthread new thread (Task); Create a corresponding execution thread based on a task
2. Task, implement Runnable interface
Override Run () method
1 class Implements runnable{2 ... 3 Public void run () {4 // executes the body, telling the system how to execute the thread 5 }6}7
3. Within the class of the execution thread, call the start () method to execute the thread
1 threadtask.start () Main program startup thread
second, the thread class
1. Method:
1Thread ()//Create an empty thread2Thread (task:runnable)// create a specified task thread3Start ():void // startup thread run () executed by JVM4IsAlive ():Boolean // Test if the front-line is executing5Join ():void // wait for thread to end6SetPriority (P:int):void // set the thread priority level,7Sleep (Mills:Long):void // Thread Sleep Mills Ms8Yield ():void // pauses the current thread and allows other threads to execute9Interrupt ():void // break thread in
2.sleep ()
Sleep () may throw interruptexception exception, Java mandatory try/catch must check exception.
3. Thread Priority
The int constants defined in Thread correspond to different priority levels:
Min_priority representative 1;
Norm_priority representative 5;
Max_priority representative 10;
Thread.norm_priority is the primary thread priority
The JVM always executes a high-priority thread and then executes the low. When the thread priority is the same, the thread is placed in the loop queue, and the loop is dispatched.
third, thread pool
When we create a thread for a task , we use the thread class, and when we create a thread for multiple Tasks , we need to use the thread pool
Executor Interface Perform a line Cheng task
Executorservice is the executor sub-interface
Executors class, static method newfixedthreadpool (int threadnum) Create a Executor object//thread pool create a fixed number of threads
1 ImportJava.util.concurrent.ExecutorService;2 Import StaticJava.util.concurrent.Executors.newFixedThreadPool;3 Public classExecutordemo {4 Public Static voidMain (String []args) {5Executorservice excutor = Newfixedthreadpool (3);//static methodwithout a new object, call Newfixedthreadpool () directly and the maximum number of threads is 36Excutor.execute (NewPrintchar (' A ', 100));//The first thread is added to the thread pool7Excutor.execute (NewPrintchar (' B ', 100)); 8Excutor.execute (NewPrintnum (100)); 9Excutor.shutdown ();// Actuator offTen } One}
Java Learning Note thread (i)