Java线程之常用函数

本文详细介绍了Java线程中的关键函数,包括设置和获取线程名字、获取当前线程、线程sleep方法的使用及异常处理、如何唤醒和终止线程。强调了sleep()方法的作用和在不同场景下的应用,以及中断线程的正确方式。
摘要由CSDN通过智能技术生成

一 设置线程名字setName()和获取线程名字getName()

【方式一】不手动设置线程名字,获取线程的默认名字,使用getName()方法,线程的默认名字格式为:Thread-0、Thread-1、Thread-2.......

public class ThreadTest05 {
	public static void main(String[] args) {
		Thread t1=new MyThread1();
		Thread t2=new MyThread1();
		//不手动设置线程名字,获取线程的默认名字
		String t1Name=t1.getName();
		String t2Name=t2.getName();
		System.out.println(t1Name);//输出"Thread-0"
		System.out.println(t2Name);//输出"Thread-1"
	}
}
class MyThread1 extends Thread{
	@Override
	public void run() {
		for(int i=0;i<10;i++) {
			System.out.println("分支线程---"+i);
		}
	}
}

【方式二】设置线程名字并获取,使用setName()和getName()方法

public class ThreadTest05 {
	public static void main(String[] args) {
		Thread t1=new MyThread1();
		Thread t2=new MyThread1();
		//设置线程名字
		t1.setName("the first thread");
		t2.setName("the second thread");
		//不手动设置线程名字,获取线程的默认名字
		String t1Name=t1.getName();
		String t2Name=t2.getName();
		System.out.println(t1Name);//输出"the first thread"
		System.out.println(t2Name);//输出"the second thread"
	}
}
class MyThread1 extends Thread{
	@Override
	public void run() {
		for(int i=0;i<10;i++) {
			System.out.println("分支线程---"+i);
		}
	}
}

二 获取当前线程Thread.currentThread()

currentThread()是Thread类的静态方法,可以使用【Thread.】的方式直接调用,获取当前线程

Thread.currentThread()出现在main方法中,当前线程就是主线程

Thread.curren

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值