线程的入门

版权声明:ByRisonBoy https://blog.csdn.net/Rison_Li/article/details/83178023

1、获取线程名

代码片段:

public class Main {
    public static void main(String[] args){
    	String threadName = Thread.currentThread().getName();
    	System.out.println(threadName);
    }
}

显示结果:main

2、获取线程id

主线程都为1

代码片段:

public class Main {
    public static void main(String[] args){
    	long threadID = Thread.currentThread().getId();
    	System.out.println(threadID);
    }
}

显示结果:1

3、修改线程名

代码片段:

public class Main {
    public static void main(String[] args){
    	Thread.currentThread().setName("新的线程名");
    	String threadName = Thread.currentThread().getName();
    	System.out.println(threadName);
    }
}

显示结果:新的线程名

4、让主方法休息

代码片段:

public class Main {
    public static void main(String[] args) throws InterruptedException{
    	Thread.currentThread().sleep(2000);
    	long threadID = Thread.currentThread().getId();
    	System.out.println(threadID);
    }

其中2000为2000毫秒也就是2秒,Thread.sleep(2000);也能得到同样的效果。

5、判断线程是否还在执行

代码片段:

public class Main {
    public static void main(String[] args) throws InterruptedException{
    	boolean isAlive = Thread.currentThread().isAlive();
    	System.out.println("主线程运行情况:"+isAlive);
    }
}

显示结果:主线程运行情况:true

6、让线程马上停止执行

代码片段:

public class Main {
    public static void main(String[] args){
    	Thread.currentThread().stop();
    	boolean isAlive = Thread.currentThread().isAlive();
    	System.out.println("主线程运行情况:"+isAlive);
    }
}

显示结果:没有显示任何结果,应为线程执行到stop();已然停止。

7、方法终止虚拟机

代码片段:

public class Main {
    public static void main(String[] args){
    	//Thread.currentThread().stop();
    	System.exit(0);//终止虚拟机
    	boolean isAlive = Thread.currentThread().isAlive();
    	System.out.println("主线程运行情况:"+isAlive);
    }
}

显示结果:没有显示任何结果,应为线程执行到System.exit(0)虚拟机已然停止,线程自然停止。

猜你喜欢

转载自blog.csdn.net/Rison_Li/article/details/83178023