在Java中,可以使用setName()方法给线程设置一个名称,使用getName()方法获取线程的名称。 Threadthread=newThread();thread.setName("MyThread");Stringname=thread.getName(); 1. 2. 3. 线程命名不显示的问题 在Java中,通过setName()方法设置线程名称后,我们期望通过getName()方法获取到的名称能正确显示。然而...
publicclassThreadExample{publicstaticvoidmain(String[]args){// 创建线程对象MyThreadmyThread1=newMyThread();MyThreadmyThread2=newMyThread();// 设置线程名称myThread1.setName("Thread1");myThread2.setName("Thread2");// 启动线程myThread1.start();myThread2.start();}}classMyThreadextendsThread{...
public class Test { public static void main(String[] args) { //Thread.currentThread()作用获取当前正在执行的线程,给main方法这个主线程设置名字: Thread.currentThread().setName("主线程"); System.out.println(Thread.currentThread().getName() + "---1---"); CThread tt = new CThread(); tt....
public class ThreadTest{ public static void main(String args[]){ //获取主线程的名字 //先通过Thread.currentThread()方法返回当前线程,然后调用该线程里的getName()方法,获取当前线程的名字 System.out.println("当前线程名字为:" + Thread.currentThread().getName()); } } 4.getName()方法,获取当前线程...
thread.setName(name):设置线程的名字。 thread.setPriority(priority):设置线程的优先级。 thread.isAlive():判断线程是否还存活着。 thread.isDaemon():判断线程是否是守护线程。 thread.setDaemon(true):将指定线程设置为守护线程。 thread.join():在当前线程中加入指定线程,使得当前线程必须等待指定线程运行结束之后...
public class ThreadDemo { public static void main(String[] args) { Thread t1 = new MyThread(); // 获取子线程默认名称 System.out.println(t1.getName()); // Thread-0 // 设置线程名称 t1.setName("1号线程"); t1.start(); Thread t2 = new MyThread(); ...
你仔细看一下 Thread b=new Thread(r);之后的两行代码你应该是要写b.setName ,你写成a.setName会...
在自定义的Runnable实现类中,可以通过Thread.setName(String name)方法设置线程名称。 在创建线程对象时,将自定义的Runnable实现类作为参数传递给Thread类的构造方法。 启动线程时,Java会自动调用自定义Runnable实现类的run()方法。 以下是一个示例: // 自定义的Runnable实现类classCustomRunnableimplementsRunnable{@Overri...
2. Setting Name to Thread We can set a custom name of the thread intwo ways: Thread class constructor The Thread.setName()method 2.1. UsingThreadConstructor We can use one of the following constructors that accept the thread name as a parameter. ...
1 创建测试类并创建ChangeThreadName的实例 thread1,这里在创建实例的同时已经将线程名修改为‘myth1’2 创建ChangeThreadName的实例 thread2 3 调用setName()方法来修改thread2线程名 4 创建ChangeThreadName的实例 thread3 5 启动所有线程开始测试。6 得到结果thread1的线程名已改为:myth1 thread2的线程名已...