The ultimate game of threading!
Get the name of the thread
package work.february.three;
/**
* @Author: 小浪
* @Description:
* @Date Created in 2021-02-03 19:58
* @Modified By:
*/
public class Demo5 {
public static void main(String[] args) {
//如何获取线程的名称
System.out.println(Thread.currentThread().getName());
new Thread(new MyRunnable()).start();
new Thread(new MyRunnable()).start();
new Thread(new MyRunnable()).start();
}
static class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
}
The output is as follows:
main
Thread-0
Thread-2
Thread-1
thread sleep
It is possible to output the following code at intervals and execute it once with a delay of 1000ms
package work.february.three;
/**
* @Author: 小浪
* @Description:
* @Date Created in 2021-02-03 20:09
* @Modified By:
*/
public class Demo6 {
public static void main(String[] args) throws InterruptedException {
for(int i =0;i<10;i++){
System.out.println(i);
Thread.sleep(1000);
}
}
}
thread blocking
All operations that consume time, such as reading files, are also called time-consuming operations.
thread interruption
package work.february.three;
/**
* @Author: 小浪
* @Description:
* @Date Created in 2021-02-03 20:13
* @Modified By:
*/
public class Demo7 {
public static void main(String[] args) throws InterruptedException {
//线程中断 自杀型 打标记
Thread thread =new Thread(new MyRunnable());
thread.start();
for(int i =0;i<3;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(1000);
}
//进行线程中断 自己进行处理
thread.interrupt();
}
static class MyRunnable implements Runnable{
@Override
public void run() {
for(int i =0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// e.printStackTrace();
System.out.println("我不想死亡啊啊");
//进行自杀
return;
}
}
}
}
}
Daemon thread
Daemon thread: guards the user thread
User threads: When a process does not contain any surviving user processes, it dies
Daemon threads can be daemonized by setting setDaemon(true) before startup!
thread safety
package work.february.three;
/**
* @Author: 小浪
* @Description:
* @Date Created in 2021-02-03 20:45
* @Modified By:
*/
public class Demo8 {
public static void main(String[] args) {
//线程不安全 就会出现 不合理的现象
MyRunnable myRunnable=new MyRunnable();
new Thread(myRunnable).start();
new Thread(myRunnable).start();
new Thread(myRunnable).start();
}
static class MyRunnable implements Runnable{
int count =10;
@Override
public void run() {
while (count > 0) {
System.out.println("正在准备取票:");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count--;
System.out.println("出票成功,余票:" + count);
}
}
}
}
This is the mistake!!!
Seeing this, don't be stingy with the likes in your hands, give a free like and follow! If you have any questions, you can contact Xiaolang: [email protected], or private message.