Java – Get a thread by Id
I worked in JMX java and I get all the thread IDs by using the getAllThreadIds () method of the interface ThreadMXBean but I need a way to kill the thread of a given ID.
ThreadMXBean tbean; tbean = ManagementFactory.getThreadMXBean(); long[] IDs=tbean.getAllThreadIds(); //. I need a way to kill the Threads which have this IDs
Best Solution
public void printAllThreadIds() < Thread currentThread = Thread.currentThread(); ThreadGroup threadGroup = getRootThreadGroup(currentThread); int allActiveThreads = threadGroup.activeCount(); Thread[] allThreads = new Thread[allActiveThreads]; threadGroup.enumerate(allThreads); for (int i = 0; i < allThreads.length; i++) < Thread thread = allThreads[i]; long System.out.println(id); >> private static ThreadGroup getRootThreadGroup(Thread thread) < ThreadGroup currentGroup = thread.getThreadGroup(); ThreadGroup parentGroup; while ((parentGroup = currentGroup.getParent()) != null) < currentGroup = parentGroup; >return currentGroup; >
But you should interrupt a Thread and not stop it.
The Thread.stop() method is deprecated, because it immediately kills a Thread . Thus data structures that are currently changed by this Thread might remain in a inconsistent state. The interrupt gives the Thread the chance to shutdown gracefully.
Related Solutions
Java – How to efficiently iterate over each entry in a Java Map
Map map = . for (Map.Entry entry : map.entrySet()) < System.out.println(entry.getKey() + "/" + entry.getValue()); >
for (var entry : map.entrySet()) < System.out.println(entry.getKey() + "/" + entry.getValue()); >
Java – How to round a number to n decimal places in Java
Use setRoundingMode , set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output.
DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.CEILING); for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324))
12 123.1235 0.23 0.1 2341234.2125
EDIT: The original answer does not address the accuracy of the double values. That is fine if you don’t care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:
Double d = n.doubleValue() + 1e-6;
To round down, subtract the accuracy.
Get Thread Id in Java
- Get Thread Id Using Thread.getId() in Java
- Get Current Thread Pool Id Using Thread.currentThread().getId() in Java
In this tutorial, we will introduce methods to get thread id in Java. We will also see how we can get the current thread’s id from a thread pool.
Get Thread Id Using Thread.getId() in Java
In this example, we have created a class Task that implements the Runnable class because we need its run() method to execute the thread. The Task class takes a thread name from its constructor, and the run() method prints it on the console when it is executed.
In the main() method, we create two Task objects in the constructor and then two threads objects in which we pass task1 and task2 to assign the tasks.
We will call the start() method using thread1 and thread2 to execute the threads. At last, once the threads have been executed, we can get each thread’s id using thread.getId() , which returns the id as a long .
public class GetThreadID public static void main(String[] args) Task task1 = new Task("Task 1"); Task task2 = new Task("Task 2"); Thread thread1 = new Thread(task1); Thread thread2 = new Thread(task2); thread1.start(); thread2.start(); System.out.println("Thread1's ID is: " + thread1.getId()); System.out.println("Thread2's ID is: " + thread2.getId()); > > class Task implements Runnable private String name; Task(String name) this.name = name; > @Override public void run() System.out.println("Executing " + name); > >
Thread1's ID is: 13 Thread2's ID is: 14 Executing Task 2 Executing Task 1
Get Current Thread Pool Id Using Thread.currentThread().getId() in Java
Thread pools are beneficial when it comes to the heavy execution of tasks. In the example below, we create a thread pool using Executors.newFixedThreadPool(numberOfThreads) . We can specify the number of threads we want in the pool.
The Task class is responsible for executing the thread in the run() method. It is a simple class that sets and gets the thread’s name passed in the constructor. To create multiple tasks, we use a for loop in which five task objects are created, and five threads are executed in the pool.
Our goal is to get the id of every thread that is being executed currently. To do that, we will use Thread.currentThread().getId() that returns the current thread’s id. In the output, we can see the ids of all the threads that execute the individual tasks.
Once the tasks are completed, we should stop executing the thread pool using threadExecutor.shutdown() . !threadExecutor.isTerminated() is used to wait until the threadExecutor has been terminated.
package com.company; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class GetThreadID public static void main(String[] args) int numberOfThreads = 5; ExecutorService threadExecutor = Executors.newFixedThreadPool(numberOfThreads); for (int i = 0; i 5; i++) Task task = new Task("Task " + i); System.out.println("Created Task: " + task.getName()); threadExecutor.execute(task); > threadExecutor.shutdown(); while (!threadExecutor.isTerminated()) > System.out.println("All threads have completed their tasks"); > > class Task implements Runnable private String name; Task(String name) this.name = name; > public String getName() return name; > @Override public void run() System.out.println("Executing: " + name); System.out.println(name + " is on thread id #" + Thread.currentThread().getId()); > >