Java multi-thread summary and demo

Source: Internet
Author: User

1. Threads can drive tasks. A task is defined by a class that implements the Runnable interface. The New Thread (Runnable) code is the best interpretation of the previous sentence. Any thread can start another thread.
Because all other threads are generated by the Main thread, the priority of the main thread is relatively high. The concept of separating a task from a thread is different from that of a thread.
 
Package com. thread. demo;
 
Public class Threademo {
 
/**
* @ Param args
*/
Public static void main (String [] args ){
Thread thread = new Thread (new Thread1 ());
Thread. start ();
System. out. println ("sdfsdfsdf ");
}
}
Class Thread1 implements Runnable {
Private final int I = 0;
Private static int count = 10;
Public void status (){
System. out. println ("the id is:" + count );
}
@ Override
Public void run (){
While (count --! = 0 ){
Status ();
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}

}

}
 
 
 
 
 
2. Use of ExecutorService thread Manager:
Package com. thread. demo;
 
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
 
Public class Executordemo {
 

Public static void main (String [] a) throws InterruptedException {
// ExecutorService creates an appropriate context for each task, that is, the thread that drives the task.
ExecutorService service = Executors. newCachedThreadPool ();
For (int I = 0; I <6; I ++ ){
Service.exe cute (new Thread2 ());
Thread. sleep (1000 );
}
Service. shutdown ();
}
}
Class Thread2 implements Runnable {

Private final int I = 0;
// Compete for the same resource
Private static int count = 10;
Public void status (){
System. out. println ("the id is:" + count );
}
@ Override
Public void run (){
While (count --> 0 ){
Status ();
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}

}

}
 
Understanding exists in the comments of the Code.
 
3. The difference between this code and the previous Code is that this Code assigns five threads to the task to be executed in advance. When the task is submitted to the thread, it does not need to be re-allocated. Reduces the overhead for thread allocation.
 
Public class Executordemo2 {
 
/**
* @ Param args
*/
Public static void main (String [] args ){
ExecutorService executor = Executors. newFixedThreadPool (5 );
For (int I = 0; I <5; I ++ ){
Executor.exe cute (new Thread3 ());
}
Executor. shutdown ();
 
}
 
}
 
 
4. When the thread manager allocates only one thread, all tasks are executed only in the submitted order. The Code is as follows:
Package com. thread. demo;
 
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
 
Public class SingleThreadDemo {
 
/**
* @ Param args
*/
Public static void main (String [] args ){
ExecutorService excutor = Executors. newFixedThreadPool (1 );
For (int I = 0; I <5; I ++ ){
Excutor.exe cute (new Single ());
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}

Excutor. shutdown ();
}
}
Class Single implements Runnable {
Private static int I = 0;
@ Override
Public void run (){
I ++;
System. out. println ("sdfsdf" + I );
}

}
 
5. futrue design mode in Java:
In java, if you need to set the maximum time for code execution, that is, timeout, you can use the java thread pool ExecutorService class with the Future interface. The Future interface is part of the JAVA standard API in java. Util. Concurrent package. The Future interface is implemented in the java thread Future mode and can be used for asynchronous computing.
 
Futrue mode can be described as follows: I have a task that has submitted Future, and future completes this task for me, during which I can do anything else.
 
 
6. For futrue and Callable interfaces in java, the Code is as follows:
Package com. thread. demo;
 
Import java. util. ArrayList;
Import java. util. concurrent. Callable;
Import java. util. concurrent. ExecutionException;
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
Import java. util. concurrent. Future;
 
Public class FutrueCllasbledemo {
 
/**
* @ Param args
* @ Throws ExecutionException
* @ Throws InterruptedException
*/
Public static void main (String [] args) throws InterruptedException, ExecutionException {
ExecutorService service = Executors. newCachedThreadPool ();
ArrayList <Future <String> arraylist = new ArrayList <Future <String> ();
For (int I = 0; I <5; I ++ ){
Arraylist. add (service. submit (new Callback ()));
}
For (Future <String> future: arraylist ){
System. out. println (future. get ());
}

Service. shutdown ();
}
 
}
 
 
Class Callback implements Callable <String> {
 
@ Override
Public String call () throws Exception {
// TODO Auto-generated method stub
Return "hello ";
}
 
}
 
 
 
7. For the demonstration of using sleep for a thread, the thread-driven task is naturally suspended due to the suspension of the current thread. The following is an example:
 
Package com. thread. demo;
 
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
 
Public class ThreadCompeteDemo {
Public static void main (String [] ){
ExecutorService service = Executors. newCachedThreadPool ();
Service.exe cute (new Threademo4 ());
Service.exe cute (new Threademo5 ());

Service. shutdown ();
}
}
 
Class Threademo4 implements Runnable {
 
@ Override
Public void run (){
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
System. out. println ("liu ");

}

}
Class Threademo5 implements Runnable {
 
@ Override
Public void run (){
System. out. println ("yangyang ");
}

}
 
Summary of some important features:
The thread priority transmits the thread importance to the scheduler.
The Excutor thread manager can close all the threads in the manager at one time.
Create a task and attach the thread to the task so that the thread can drive the task.
In java, the Thread class does not execute any operations, but it only drives its tasks.
The Java thread mechanism is based on the low-level p thread mode from c.
The ThreadFactory factory is usually used together with ExecutorService. Generally, the former is located in the latter constructor. ThreadFactory mainly customizes certain behaviors and attributes for the thread generated by the ExecutorService thread manager.

Author: "690360459-qq-com"
 

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.