Basic knowledge and common methods of the first-known multi-thread

Source: Internet
Author: User
Tags thread class

1. Description of threads and processes:

1.1 Process: Each process has its own code and data space (process context), there is a large overhead of switching between processes, and a process contains 1~n threads. (Process is the smallest unit of resource allocation)
  

1.2 Threads: The same class of threads share code and data space, each thread has a separate run stack and program counter (PC), and the thread switching overhead is small. (Thread is the smallest unit of CPU scheduling)

2. Common ways to implement multithreading:

Inherit the thread class extends thread

Implement Runnable interface implements Runnable

Internal Anonymous class

Thread t = new Thread (new Runnable () {    
});

3. Common ways to implement multithreading:

Runnable interfaces are recommended: Two reasons: 1 classes in Java only support single inheritance, while interfaces support multiple inheritance
2 easily implement resource sharing between multiple threads using the Runnable interface

4. Five states of the thread:

5. Common function Description: 5.1:join thread (Control thread):
Thread provides a method--join method that lets one thread wait for another thread to finish, and when a join method of another thread is called in a program execution stream, the calling thread is blocked until the join thread joined by the Join method finishes executing.

Liezi:

1 /**2 * Created by 123 on 2017/07/02.3  */4  Public classTestjoin {5      Public Static voidMain (string[] args)throwsinterruptedexception {6         NewJointhread ("New Thread"). Start ();7          for(inti = 0; I < 10; i++) {8                if(i==5){9Jointhread j1=NewJointhread ("Thread to be join");Ten J1.start (); One J1.join (); A                } -System.out.println (Thread.CurrentThread (). GetName () + "" +i); -         } the     } -}
Join method Use (test Class)
1 /**2 * Created by 123 on 2017/07/02.3  */4  Public classJointhreadextendsThread {5      PublicJointhread (String name) {6         Super(name);7     }8 9      Public voidrun () {Ten          for(inti=1;i<=10;i++){ OneSystem.out.println (Thread.CurrentThread (). GetName () + "" +i); A         } -     } -}
Thread Execution Body

5.2:yield thread (thread concession): The priority of the thread Thread.yield () method is to pause the currently executing thread object and execute other threads.
Yield () should be done to get the current running thread back to the operational state to allow other threads with the same priority to get the run opportunity. Therefore, the purpose of using yield () is to allow appropriate rotation between threads of the same priority. However, in practice there is no guarantee that yield () will be compromised, as the thread of the concession may be checked again by the thread scheduler.
1 ImportJavax.naming.Name;2 3 /**4 * Created by 123 on 2017/07/02.5  */6  Public classThreadyeildextendsThread {7 String name;8 9      Publicthreadyeild (String name) {Ten         Super(name); One          This. Name =name; A     } -  - @Override the      Public voidrun () { -          for(inti = 0; I < 50; i++) { -System.out.println ( This. GetName () + "" +i); -             if(i==30){ + Thread.yield (); -             } +         } A     } at}
Thread Execution Body
1 ImportJavax.naming.Name;2 3 /**4 * Created by 123 on 2017/07/02.5  */6  Public classThreadyeildextendsThread {7 String name;8 9      Publicthreadyeild (String name) {Ten         Super(name); One          This. Name =name; A     } -  - @Override the      Public voidrun () { -          for(inti = 0; I < 50; i++) { -System.out.println ( This. GetName () + "" +i); -             if(i==30){ + Thread.yield (); -             } +         } A     } at}
Yeild Method (test Class)

The difference between the 5.3:sleep () function and the yield function: the difference between sleep () and yield ():
1:sleep () causes the current thread to go to a standstill, so the thread executing sleep () will not be executed for a specified period of time;
Yield () simply returns the current thread back to the executable state, so the thread executing yield () is likely to be executed immediately after entering the executable state.
The 2:sleep () function can also allow a lower-priority thread to run 5.4 Daemon threads:
1 /**2 * Created by 123 on 2017/07/02.3  */4  Public classBackgroundthreadImplementsRunnable {5      Public voidrun () {6           for(inti=1;i<100000000;i++){7SYSTEM.OUT.PRINTLN ("Background thread executes section" +i+ "Times");8              Try {9Thread.Sleep (7);Ten}Catch(interruptedexception e) { One e.printstacktrace (); A              } -          } -     } the}
Background Thread
1 /**2 * Created by 123 on 2017/07/02.3  */4  Public classMythreadsextendsThread {5 @Override6      Public voidrun () {7          for(inti = 1; I <= 4; i++) {8SYSTEM.OUT.PRINTLN ("Thread 1" + i + "Second execution");9             Try {TenThread.Sleep (7); One}Catch(interruptedexception e) { A e.printstacktrace (); -             } -         } the     } -}
Foreground Thread
1 /**2 * Created by 123 on 2017/07/02.3 * Daemon Thread4  */5  Public classTestthread {6     //if the foreground thread executes I, the background thread executes i+1 times because there is also a main thread7      Public Static voidMain (string[] args) {8Thread T1 =Newmythreads ();9Thread t2 =NewThread (NewBackgroundthread ());TenT2.setdaemon (true);//Set as daemon thread One T1.start (); A T2.start (); -     } -}
Test Class

The conclusion is that if the foreground thread executes I, then the background thread executes i+1, because there is also a main thread.

5.4: Priority of Thread (1~10)
SetPriority (): Change the priority of the thread. min_priority = 1
Norm_priority = 5
Max_priority = 10

Basic knowledge and common methods of the first-known multi-thread

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.