currentThread方法是Thread类的一个静态方法,用来获取当前运行的代码段,正在被哪个线程调用。我们先来看一眼源码。 是一个native方法。直接与系统层面做交互。下面看一段代码 public static void main(String[] args) { String name = Thread.currentThread().getName(); Sy
Thread.currentThread.getName()=main //实体是指现在正在发生的线程:main线程 this.getName()=Thread-0 //实例:当前实例是“死的线程”,默认赋值是:Thread-0 false // 实体并不是实例 ---MyThreadbegin--- ---run begin--- Thread.currentThread.getName()=test//实体是指现在正在发生的线程:test线程 th...
Thread.currentThread().getName():获取到的是new Thread(myThread)这个类的对象. 因为获取到的是两个不同的对象,所以会出现Thread-0 和Thread-1 而且threadInitNumber这个变量是一个静态的. nextThreadNum()这个方法是synchronized修饰的,不会造成同步问题. 总结:实际上new Thread(myThread)会将myThread应用的对象...
publicclassGetCurrentThreadName{publicstaticvoidmain(String[]args){// 步骤一:获取当前执行的线程对象ThreadcurrentThread=Thread.currentThread();// 步骤二:从线程对象中获取线程的名称StringthreadName=currentThread.getName();// 步骤三:打印线程的名称System.out.println("当前执行的线程的名称是:"+threadName);...
// 获取线程的名字ThreadcurrentThread=Thread.currentThread();StringthreadName=currentThread.getName();System.out.println("线程名字:"+threadName); 1. 2. 3. 4. 通过Thread.currentThread()方法获取当前线程,然后调用getName()方法获取线程的名字。
Thread thread = Thread.currentThread(); 2、获取和设置线程名称 获取和设置线程名称的API如下: 代码示例: public class ThreadDemo { public static void main(String[] args) { Thread t1 = new MyThread(); // 获取子线程默认名称 System.out.println(t1.getName()); // Thread-0 ...
Thread t = new Thread(); String threadName = t.getName(); System.out.println("Thread name: " + threadName); 复制代码 另外,可以使用Thread.currentThread()方法来获取当前执行线程的引用,然后调用getName()方法来获取当前线程的名称,例如: Thread currentThread = Thread.currentThread(); String currentThr...
public class ThreadTest{ public static void main(String args[]){ //先通过Thread.currentThread()获取当前线程 //调用当前线程的setName()方法,为当前线程设置名字。 Thread.currentThread().setName("主线程:"); System.out.println("当前线程名字为:" + Thread.currentThread().getName()); ...
currentThread(); String name = t.getName(); System.out.println("name=" + name); } public static void main(String[] args) { TwoThreadGetName tt = new TwoThreadGetName(); tt.start(); for (int i = 0; i < 10; i++) { tt.printMsg(); } } }...
下面举例解释Thread.currentThread()和this的区别,前者指当前线程,也就是正在执行代码的线程。后者指当前的对象,也就是代码所在方法所属的对象。 如果把Machine类的run()方法中的“currentThread()”改为“this”: for(inta=0;a<100;a++)System.out.println(this.getName()+":"+a); ...