1. Inherit Thread
Mainly master: thread initialization, startup, and correct handling of interrupts (interrupted)
public class Demo1 {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+:running...);
}
}
2. Implement Runnable
Source code analysis, why the run method of Runnable is called
public class Demo2 {
public static void main(String[] args) {
MyRunnable task = new MyRunnable();
new Thread(task).start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+:running);
}
}
3. The way of anonymous inner class (the case where the thread is only created once)
There are two ways
public class Demo3 {
public static void main(String[] args) {
new Thread(){
public void run() {
System.out.println (create thread by way of anonymous inner class);
};
}.start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println (by implementing an anonymous Runnable subclass);
}
}).start();
}
}
I leave a question for everyone. If both are considered, which one will be used in the implementation? Why?
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(you guessed it was running this section?);
}
}){
public void run() {
System.out.println (or this paragraph?);
};
}.start();
4. Thread with return value, implement Callable interface
Implement the call method
FutureTask encapsulates tasks
5, the way to use the timer
Timer, TimerTask, execute timed tasks
6, the way to use the thread pool
Create different thread pools for task execution through Executors
7. Lambda expressions (functional programming) new features provided by JDK1.8
Lambda expression code is concise, easy to implement, good support for concurrency, and high performance
We observe the running results by printing a set of data, and found that the order is inconsistent, indicating that it is a multi-threaded mode