target
-
Thread concept
-
The difference between thread and process
-
Serial, parallel and concurrent concepts
-
-
Implementation of thread
-
Thread life cycle
-
Common methods of thread
Thread concept
Difference between program and process
The program is static, the process is dynamic, and the program is binary code stored on a certain medium. The process corresponds to the execution process of the program. The system does not need to create a process for a non executing program. Once the process is created, it is in a changing dynamic process, corresponding to a changing context.
The program is permanent and the process exists temporarily. The permanence of the program is relative to the process. As long as it is not deleted, it can be permanently stored in the media.
Difference between process and thread
(1) Scheduling: thread is the basic unit of scheduling and allocation, and process is the basic unit of owning resources
(2) Concurrency: not only processes can execute concurrently, but also multiple threads of the same process can execute concurrently (3) Owning resources: a process is an independent unit that owns resources. Threads do not own system resources, but can access resources belonging to the process (4) System overhead: when creating or undoing a process, because the system has to allocate and recycle resources for it, the system overhead is significantly greater than that when creating or undoing a thread.
Serial, concurrent and parallel
-
Serial multiple instructions are executed from top to bottom,
-
Concurrent each thread will preempt the time slice through the line, so it will have the effect of switching back and forth, but not at the same time. Without time arrangement, it will be in a waiting state
-
Parallel multiple cpu cores execute multiple threads simultaneously without affecting each other and at the same time
Implementation of thread
Four ways to implement threads in java
-
Inherit Thread class
-
Implement Runnable interface
-
Implement Callable interface
-
Use thread pool
Inherit Thread class
-
Inherit Thread class
-
Override run method
-
Call start to start the thread
Case realization 1
Two threads are designed. One thread is responsible for printing all even numbers within 1 ~ 100; Then, another thread is responsible for printing all odd numbers within 1 ~ 100.
class Thread1 extends Thread{ public void run(){ for (int i = 0; i <=100 ; i+=2) { System.out.println(Thread2.currentThread().getName()+"Odd number"+i); } } } class Thread2 extends Thread{ public void run(){ for (int i = 0; i <=100 ; i+=2) { System.out.println(Thread2.currentThread().getName()+"even numbers"+i); } } } public class ZuoYe1 { public static void main(String[] args) { Thread1 t1=new Thread1(); Thread2 t2=new Thread2(); t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); t1.start(); t2.start(); } }
Case 2
Implement a thread to scan all text files in a directory (including java, txt and html) and print the text content.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class ZuoYe02 { public static void main(String[] args) { new Thread(() -> { File file = new File("D:\\workspace03"); readFile(file); }).start(); } public static void readFile(File f) { if (f.isDirectory()) { File[] files = f.listFiles(); if (files != null) { for (File file : files) { readFile(file); } } } else { System.out.println(f.getName()); //read file try { //Get file //Get the character stream read from the file FileReader fileReader = new FileReader(f); //Get buffered character stream BufferedReader bufferedReader = new BufferedReader(fileReader); String readLine = null; while((readLine = bufferedReader.readLine()) != null){ System.out.println(readLine); } fileReader.close(); bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } } } }
Case 3
Someone is watching a TV series. When he sees Episode 10 from Episode 1 to 88, a courier comes. After receiving the courier, he continues to watch TV.
public class ZuoYe03 { public static void main(String[] args) { new Thread(()->{ for (int i = 1; i <89 ; i++) { System.out.println(Thread.currentThread().getName() + "===" + "See the second" + i + "level"); try{ Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } if(i==10){ Thread t1=new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "===" + "Here comes the courier"); try{ Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "===" + "The express is finished"); } }); t1.start(); try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
Case 4
-
Multi thread simulated tortoise rabbit race:
The tortoise and the rabbit have a 1000 meter race. The rabbit advances 5 meters and the tortoise can only advance 1 meter.
But rabbits rest for 500 milliseconds every 20 meters, while turtles rest for 500 milliseconds every 100 meters.
Whoever gets to the end first ends the program and displays the winner
public class ZuoYe04 { public static void main(String[] args) { Result r = new Result(); new Thread(() -> { for (int i = 1; i <= 1000; i++) { System.out.println("The tortoise ran away" + i + "rice"); try { Thread.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } if (i >= 1000) { r.isWin = true; System.out.println("The tortoise won" + i); break; } if (i % 100 == 0) { try { System.out.println("Where is the tortoise"+i+"Start to rest at meters"); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(() -> { int m = 0; for (int j = 1; j <= 200; j++) { if(r.isWin){ System.out.println("The rabbit ran away" + m + "rice............"); break; } m += 5; System.out.println("The rabbit ran away" + m + "rice"); try { Thread.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } if (m >= 1000) { System.out.println("The rabbit won" + j); } if (m % 20 == 0) { try { System.out.println("Rabbit in"+j*5+"Start to rest at meters"); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } } class Result{ boolean isWin = false; }
Thread life cycle
Thread status:
-
NEW new
-
Ready / ready START
-
Run RUNNING
-
BLOCKING
-
Death
Common methods of thread
common method
method | introduce |
---|---|
start() | start-up |
stop() | Stop (disabling may cause thread deadlock and other problems). Stopping the thread can end the execution of run |
String getName() | Get the name of the thread |
setName(String) | Set thread name |
sleep(long) | Sleep in milliseconds |
setPriority(int) | The higher the priority of the thread (1 ~ 10 from low to high), the higher the probability of grabbing the CPU |
setDaemon(boolean) | Set to background thread true. Background threads serve other threads. If no other threads exist, they will die automatically; Use case: GC is a background thread |
join() | The addition (merging) of threads allows other threads to execute first, and then execute their own instructions |
Personal summary
The above induction is the threshold of thread learning. If you want to be proficient in using it, you have to knock more and practice more‘
There is a road to the mountain of books. Diligence is the path. There is no end to learning. It is hard to make a boat