问题 更新时间2023/10/31 14:58:00
实现Runnable接口创建线程,并在线程内提示线程名称等相关信息。
实现Runnable接口创建线程,并在线程内提示线程名称等相关信息。
//定义Java类实现Runnable接口
public class MyRunnable implements Runnable{
//重写run方法,并在方法中编写需要在线程中处理的逻辑
@Override
public void run() {
//获取当前线程
Thread th = Thread.currentThread();
//获取线程编号
long threadId = th.getId();
//获取线程名称
String threadName = th.getName();
System.out.println( "线程名称为:"+threadName+" 线程编号:"+threadId ); }
}
public class Test {
public static void main(String[] args)
{
//获取当前已经存在的主线程
Thread th = Thread.currentThread();
//线程名称
String name = th.getName();
//线程编号
long id = th.getId();
System.out.println( "线程编号:"+id+" 线程名字:"+name );
//通过Thread(Runnable target)构造方法创建线程对象
MyRunnable mr = new MyRunnable();
Thread thth = new Thread(mr);
//开启线程执行
thth.start();
}
}
出自:国家开放大学 >> 国家开放大学移动开发技术导论
答案