Multi-threading concept
Concurrency|concurrency
- Parallel: Multiple instructions executed simultaneously on multiple CPU s
- Concurrent: Multiple instructions executed alternately on a single CPU
Process|Thread
- Processes: Processes in progress such as: word
- Independence: An independent unit that runs, distributes, and schedules resources independently
- Dynamics: A process is a complete execution of a program, which is generated dynamically and then dies out
- Concurrency: Any process can execute concurrently with other independent processes
- Threads: A single sequential control flow in a process, which is a path of execution such as word write checking
- Single-threaded program: A process with one thread execution path and vice versa, multiple threads
Multithreaded implementation
Inherit Thead Class
- Definition class MyThread inherits Thead class
- Override run() method in MyThread class
- Create MyThead class object
- Start Thread
// MyThread .java package com.su27.demo1; public class MyThread extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("Thread Open"+i); } } }
// Demo .java package com.su27.demo1; public class Demo { public static void main(String[] args){ MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.start(); t2.start(); } }
A minor question
- Why override run methods
Encapsulate executed code by thread using run() - The difference between start and run calls
run(): Do not start thread calls
start(): Start a thread call
Implement Runnable Interface Implementation
- Define MyRunnable class to implement Runnable interface
- Override run() method in MyRunnable class
- Create MyRunnable class object
- Create Thread class object with MyRunnable object as construction method parameter
MyRunnable .java
package com.su27.demo2; public class MyRunnable implements Runnable{ @Override public void run(){ // Execute code after thread starts for (int i = 0; i < 100; i++) { System.out.println("Second way to achieve multithreading" + i); } } }
Demo.java
package com.su27.demo2; public class Demo { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t1 = new Thread(mr); t1.start(); Thread t2 = new Thread(mr); t2.start(); } }
Implement with Callable and Future interfaces
- Define class MyCallable to implement Callable interface
- Override the call() method in the MyCallable class
- Create MyCallable class object
- Create FutureImplementation Class FutureTask object with MyCallable object as constructor parameter
- Create Thread class object with FutureTask object as construction method parameter
- Start Thread
- Get the result of thread execution
MyCallable.java
package com.su27.demo3; import java.util.concurrent.Callable; public class MyCallable implements Callable<String> { @Override public String call() throws Exception{ for (int i = 0; i < 100; i++) { System.out.println("Load Progress"+i+"%"); } // Return value indicates the result after the thread has finished running return "Loaded"; } }
Demo.java
package com.su27.demo3; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Demo { public static void main(String[] args) throws ExecutionException, InterruptedException { // Execute call method after thread is opened MyCallable mc = new MyCallable(); //The middleware gets the result of the thread execution and can also be passed to the Thread object as a parameter FutureTask<String> ft = new FutureTask<>(mc); //Create Thread Object Thread t1 = new Thread(ft); //Open Thread t1.start(); // Get the result of thread execution String s = ft.get(); System.out.println(s); } }
Implementation Comparison
Advantage | shortcoming | |
---|---|---|
Implement Runnale, Callable interfaces | Extensibility, interface implementation and inheritance of other classes | Programming is complex and the Thread class method cannot be used directly |
Inherit Thread Class | Simple programming, you can use the Thread class method directly | Poor extensibility, cannot inherit other classes |
Thread class
Get Thread Name Method (3)
package com.su27.getName; /** * Get Thread Name * 1.Get the thread name using the method getName() in the Thread class * 2. Get the currently executing thread first, then use the getName method in the thread to get the thread name * */ public class MyThread extends Thread { // Override the run method in the Thread class to set the thread task @Override public void run() { // 1.Get Thread Name // String name = getName(); // System.out.println(name); // 2. Thread.currentThread() // Thread t = Thread.currentThread(); // System.out.println(t); // 3. Chain // System.out.println(Thread.currentThread().getName()); } }
Set Thread Name Method (2)
- MyThread.java
package com.su27.setName; public class MyThread extends Thread{ public MyThread(){ } public MyThread(String name){ super(name);// Pass name to parent and parent Thread to child } @Override public void run(){ // Get Thread Name Output System.out.println(Thread.currentThread().getName()); } }
- Demo.java
package com.su27.setName; public class Demo { public static void main(String[] args) { // Open multithreading MyThread mt = new MyThread(); mt.setName("My Threads"); mt.start(); // Modified with parameters new MyThread("Modified with parameters").start(); } }
sleep method - suspend thread
package com.su27.sleep; public class Demo { public static void main(String[] args) { // Analog stopwatch for (int i = 0; i < 100; i++) { System.out.println(i); // Using the Thread sleep method try { // sleep throws a try...catch Thread.sleep(1000); }catch (InterruptedException e) { e.printStackTrace(); } } } }