We know that multi-threads are executed concurrently in the current operating system, which will result in a series of various operations of threads. Let's quickly browse the various basic operations of threads;
1. Thread creation
There are many ways to create threads, the following are the recommended ways
Thread thread =new Thread(()->{
System.out.println("thread begin");
);
2. Thread interruption
We can use Thread’s own flag bit
Thread thread=new Thread(()->{
while (!Thread.currentThread().isInterrupted()){//静态方法,获取到当前线程的实例。
System.out.println("线程运行ing......");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//e.printStackTrace();
// 1.立即退出
// break;
// 2.稍后退出
System.out.println("线程即将退出");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
break;
}
}
System.out.println("线程已经退出");
});
thread.start();
Thread.sleep(5000);//sleep操作就是阻塞
System.out.println("控制新线程退出");
thread.interrupt();
3. Thread waiting (join)
The execution order between threads is completely random, depending on the system's scheduling. But we can control the ending order of two threads through join
//main等待t2,t2等待t1
System.out.println("main begin");
Thread t1=new Thread(()->{
System.out.println("t1 begin");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1 end");
});
Thread t2=new Thread(()->{
System.out.println("t2 begin");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 end");
});
t1.start();
t1.join();
t2.start();
t2.join();
System.out.println("main end");
4. Thread sleep
Thread.slepp(1000); //Unit is milliseconds
5. Get the thread instance
call start