线程的究极玩法!
作者:互联网
线程的究极玩法!
获取线程的名称
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());
}
}
}
输出如下:
main
Thread-0
Thread-2
Thread-1
线程的休眠
可以实现间隔输出 以下代码延时 休息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);
}
}
}
线程阻塞
所有比较消耗时间的操作,比如读取文件,也称耗时操作.
线程中断
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;
}
}
}
}
}
守护线程
守护线程:守护用户线程
用户线程:当一个进程不包含任何存活的用户进程时,进行死亡
在启动之前设置setDaemon(true)就可以进行守护线程!
线程安全性
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);
}
}
}
}
这就是错误!!!
看到这里了,就不要吝啬手里的赞了,给个免费的赞和关注吧!如果有什么问题可以联系小浪:3090215793@qq.com,或者私信.
标签:究极,MyRunnable,Thread,玩法,线程,println,new,public 来源: https://blog.csdn.net/AzirBoDa/article/details/113618543