publicclassThreadExample{publicstaticvoidmain(String[]args){// 创建线程对象MyThreadmyThread1=newMyThread();MyThreadmyThread2=newMyThread();// 设置线程名称myThread1.setName("Thread1");myThread2.setName("Thread2");// 启动
在Java中,可以使用setName()方法给线程设置一个名称,使用getName()方法获取线程的名称。 Threadthread=newThread();thread.setName("MyThread");Stringname=thread.getName(); 1. 2. 3. 线程命名不显示的问题 在Java中,通过setName()方法设置线程名称后,我们期望通过getName()方法获取到的名称能正确显示。然而...
// 输出 threadName:my-custom-thread-name-1, threadGroupName:main, threadId:13 // 方式二:使用Thread对象的setName方法,设置线程名称 Thread thread = new Thread(() -> { String threadName = Thread.currentThread().getName(); String threadGroupName = Thread.currentThread().getThreadGroup().getNa...
LOGGER.info("当前线程-线程组名字:" + currentThread.getThreadGroup().getName() + "\n");//通过thread.setName(name)设置线程名LOGGER.info("通过thread.setName(name)设置线程名"); currentThread.setName("张三");//通过thread.setPriority(priority)设置优先级LOGGER.info("通过thread.setPriority(priority)...
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...
一、Thread的常用方法 1.run()方法 2.start()方法 3.currrentThread()方法,返回当前执行代码的线程,该方法为静态方法,直接通过Thread类名调用 4.getName()方法,获取当前线程的名字 5.setName()方法,设置当前线程名字 6.yield()方法,释放当前线程的操作 ...
Thread t = new Thread(r); // 这里设置了线程池名称,使用counter区分不同线程 t.setName(String.format(builder.getNameFormat(), counter.getAndIncrement())); return t; }; } } 查看源码ExecutorService源码,发现预留了线程工厂的入参 // ExecutorService newFixedThreadPool 预留了ThreadFactory ...
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. ...