多线程之Thread的常用方法、匿名内部类实现创建多线程

Thread类的常用方法

获取线程的名称

  • 使用Thread类中的getName()方法
String name = getName();
System.out.println(name);
  • 可以获取当前正在执行的线程,static Thread currentThread()返回当前正在执行的线程对象的引用
    代码比较简单,可以直接输出。
System.out.println(Thread.currentThread()).getName());//输出当前证正在执行的线程的名称

设置线程名称
使用Thread类中的方法setName(string)

Mythred mt = new MyThread();
mt.setName("naem");
//Mythread是继承了Thread类的类的名称

使线程休眠sleep

public static void sleep (long millis);
//使当前正在执行的线程暂停指定的毫秒数。1s=0.0001ms

举个栗子
通过sleep来写一个程序模拟秒表
代码如下

public class time {
	public static void main(String[] args){
		for(int i=1;i<=60;i++)
		{
			System.out.println(i);
			try{
			Thread.sleep(1000);}//使用sleep使当前线程暂停1秒钟
			catch(InterruptedException e){
			e.printStackTrance();
			}
		}
	}
}

匿名内部类实现创建多线程

发布了53 篇原创文章 · 获赞 6 · 访问量 4885

猜你喜欢

转载自blog.csdn.net/m0_46193982/article/details/104973733