Java check running threads

How to check active threads in java

Description The java.lang.Thread.activeCount() method returns the number of active threads in the current thread’s thread group. This method returns the number of active threads in the current thread’s thread group.

Java.lang.Thread.activeCount() Method

Description

The java.lang.Thread.activeCount() method returns the number of active threads in the current thread’s thread group.

Declaration

Following is the declaration for java.lang.Thread.activeCount() method

public static int activeCount()

Parameters

Return Value

This method returns the number of active threads in the current thread’s thread group.

Exception

Example

The following example shows the usage of java.lang.Thread.activeCount() method.

package com.tutorialspoint; import java.lang.*; public class ThreadDemo < public static void main(String[] args) < Thread t = Thread.currentThread(); t.setName("Admin Thread"); // set thread priority to 1 t.setPriority(1); // prints the current thread System.out.println("Thread = " + t); int count = Thread.activeCount(); System.out.println("currently active threads = " + count); Thread th[] = new Thread[count]; // returns the number of threads put into the array Thread.enumerate(th); // prints active threads for (int i = 0; i < count; i++) < System.out.println(i + ": " + th[i]); >> >

Let us compile and run the above program, this will produce the following result −

Thread = Thread[Admin Thread,1,main] currently active threads = 1 0: Thread[Admin Thread,1,main]

What is active thread group in Java?, As you noted, the terminology «active thread group» appears in the javadoc for ThreadGroup::activeGroupCount . An active thread group is a

Читайте также:  Html style font letter spacing

tl;dr

Compare the state of the thread:

thread.getState().equals( Thread.State.RUNNABLE ) 

Here is an example making a stream from your list of Thread objects.

threads .stream() .filter( thread -> thread.getState().equals( Thread.State.RUNNABLE ) ) .count() // Or collect them: `.toList()` 

Or count all active threads:

Details

I have no experience in this, but looking the Javadoc for Thread , I see getState . That method returns a Thread.State enum object. Documentation says:

A thread can be in one of the following states, as quoted from the doc:

  • NEW
    A thread that has not yet started is in this state.
  • RUNNABLE
    A thread executing in the Java virtual machine is in this state.
  • BLOCKED
    A thread that is blocked waiting for a monitor lock is in this state.
  • WAITING
    A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  • TIMED_WAITING
    A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
  • TERMINATED
    A thread that has exited is in this state.

So loop your Thread objects, fetch their State , and see if it is RUNNABLE .

But if you just want a count of all active threads, call Thread.activeCount() .

This function counts all the active Threads in the process:

java.lang.Thread.activeCount(); 

And of course, you could use getState() instead of isActive() to check the current thread’s state.

How To Display All Running Threads In Java ?, The getAllStackTrace() method gives a stack trace of all the running threads. Then we make a set of the keys of that element because the method

Java Examples — Display all running Thread?

Problem Description

How to display all running Thread?

Solution

Following example demonstrates how to display names of all the running threads using getName() method.

public class Main extends Thread < public static void main(String[] args) < Main t1 = new Main(); t1.setName("thread1"); t1.start(); ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); int noThreads = currentGroup.activeCount(); Thread[] lstThreads = new Thread[noThreads]; currentGroup.enumerate(lstThreads); for (int i = 0; i < noThreads; i++) System.out.println("Thread No:" + i + " = " + lstThreads[i].getName()); >>

Result

The above code sample will produce the following result.

Thread No:0 = main Thread No:1 = thread1

How to find a Java thread running on Linux with ps -axl?, «ps -eLf» does, in the «LWP» column. («LWP» is short for «lightweight process», which is another name for a thread.) Within Java, the Thread.

You can increment a counter when the task starts and decrement it when it finishes.

public void run() < AtomicInteger counter = counterMap.computeIfAbsent(key, k ->new AtomicInteger()); counter.incrementAndGet(); try < doRun(); >finally < counter.getAndDecrement(); >> 

Make your key static so that it will keep its values among threads.

 public class Abc extends Thread < private static Mapmap = new ConcurrentHashMap<>(); private String key; public void run() < synchronized (key) < Integer current = map.get(key); if(null == current) < map.put(key, 1); >else < map.put(key, current +1); >> //Run execution code here. synchronized (key) < Integer current = map.get(key); map.put(key, current -1); >> > 

Capturing a Java Thread Dump, jstack is a command-line JDK utility we can use to capture a thread dump. It takes the pid of a process and displays the thread dump in the

Источник

How to check if thread is running java

Solution 2: Solution using CyclicBarrier label0 — cyclic barrier is created with number of parties equal to the number of executing threads plus one for the main thread of execution (in which startDownload() is being executed) label 1 — n-th DownloadingThread enters the waiting room label 3 — NUMBER_OF_DOWNLOADING_THREADS have entered the waiting room. If it is the last one i.e. already NUMBER_OF_DOWNLOADING_THREADS have entered it, including the main thread of execution, main thread will continue its execution only when all the other threads have finished downloading.

Java Examples — Checking an Alive Thread

Problem Description

How to check a thread is alive or not ?

Solution

Following example demonstrates how to check a thread is alive or not by extending Threda class and using currentThread() method.

public class TwoThreadAlive extends Thread < public void run() < for (int i = 0; i < 10; i++) < printMsg(); >> public void printMsg() < Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name = " + name); >public static void main(String[] args) < TwoThreadAlive tt = new TwoThreadAlive(); tt.setName("Thread"); System.out.println("before start(), tt.isAlive() = " + tt.isAlive()); tt.start(); System.out.println("just after start(), tt.isAlive() = " + tt.isAlive()); for (int i = 0; i < 10; i++) < tt.printMsg(); >System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive()); > >

Result

The above code sample will produce the following result.

before start(), tt.isAlive() = false just after start(), tt.isAlive() = true name = main name = main name = main name = main name = main name = main name = main name = main name = main name = Thread name = main name = Thread The end of main(), tt.isAlive() = true name = Thread name = Thread name = Thread name = Thread name = Thread name = Thread name = Thread name = Thread

How to check if a thread is sleeping?, You can call Thread.getState() on and check if the state is TIMED_WAITING . Note, however that TIMED_WAITING doesn’t necessarily mean that

There are a number of ways you can do this:

  1. Use Thread.join() in your main thread to wait in a blocking fashion for each Thread to complete, or
  2. Check Thread.isAlive() in a polling fashion — generally discouraged — to wait until each Thread has completed, or
  3. Unorthodox, for each Thread in question, call setUncaughtExceptionHandler to call a method in your object, and program each Thread to throw an uncaught Exception when it completes, or
  4. Use locks or synchronizers or mechanisms from java.util.concurrent, or
  5. More orthodox, create a listener in your main Thread, and then program each of your Threads to tell the listener that they have completed.

How to implement Idea #5? Well, one way is to first create an interface:

public interface ThreadCompleteListener

then create the following class:

public abstract class NotifyingThread extends Thread < private final Setlisteners = new CopyOnWriteArraySet(); public final void addListener(final ThreadCompleteListener listener) < listeners.add(listener); >public final void removeListener(final ThreadCompleteListener listener) < listeners.remove(listener); >private final void notifyListeners() < for (ThreadCompleteListener listener : listeners) < listener.notifyOfThreadComplete(this); >> @Override public final void run() < try < doRun(); >finally < notifyListeners(); >> public abstract void doRun(); > 

and then each of your Threads will extend NotifyingThread and instead of implementing run() it will implement doRun() . Thus when they complete, they will automatically notify anyone waiting for notification.

Finally, in your main class — the one that starts all the Threads (or at least the object waiting for notification) — modify that class to implement ThreadCompleteListener and immediately after creating each Thread add itself to the list of listeners:

NotifyingThread thread1 = new OneOfYourThreads(); thread1.addListener(this); // add ourselves as a listener thread1.start(); // Start the Thread 

then, as each Thread exits, your notifyOfThreadComplete method will be invoked with the Thread instance that just completed (or crashed).

Note that better would be to implements Runnable rather than extends Thread for NotifyingThread as extending Thread is usually discouraged in new code. But I’m coding to your question. If you change the NotifyingThread class to implement Runnable then you have to change some of your code that manages Threads, which is pretty straightforward to do.

Solution using CyclicBarrier

public class Downloader < private CyclicBarrier barrier; private final static int NUMBER_OF_DOWNLOADING_THREADS; private DownloadingThread extends Thread < private final String url; public DownloadingThread(String url) < super(); this.url = url; >@Override public void run() < barrier.await(); // label1 download(url); barrier.await(); // label2 >> public void startDownload() < // plus one for the main thread of execution barrier = new CyclicBarrier(NUMBER_OF_DOWNLOADING_THREADS + 1); // label0 for (int i = 0; i < NUMBER_OF_DOWNLOADING_THREADS; i++) < new DownloadingThread("http://www.flickr.com/someUser/pic" + i + ".jpg").start(); >barrier.await(); // label3 displayMessage("Please wait. "); barrier.await(); // label4 displayMessage("Finished"); > > 

label0 — cyclic barrier is created with number of parties equal to the number of executing threads plus one for the main thread of execution (in which startDownload() is being executed)

label 1 — n-th DownloadingThread enters the waiting room

label 3 — NUMBER_OF_DOWNLOADING_THREADS have entered the waiting room. Main thread of execution releases them to start doing their downloading jobs in more or less the same time

label 4 — main thread of execution enters the waiting room. This is the ‘trickiest’ part of the code to understand. It doesn’t matter which thread will enter the waiting room for the second time. It is important that whatever thread enters the room last ensures that all the other downloading threads have finished their downloading jobs.

label 2 — n-th DownloadingThread has finished its downloading job and enters the waiting room. If it is the last one i.e. already NUMBER_OF_DOWNLOADING_THREADS have entered it, including the main thread of execution, main thread will continue its execution only when all the other threads have finished downloading.

You should really prefer a solution that uses java.util.concurrent . Find and read Josh Bloch and/or Brian Goetz on the topic.

If you are not using java.util.concurrent.* and are taking responsibility for using Threads directly, then you should probably use join() to know when a thread is done. Here is a super simple Callback mechanism. First extend the Runnable interface to have a callback:

public interface CallbackRunnable extends Runnable

Then make an Executor that will execute your runnable and call you back when it is done.

public class CallbackExecutor implements Executor < @Override public void execute(final Runnable r) < final Thread runner = new Thread(r); runner.start(); if ( r instanceof CallbackRunnable ) < // create a thread to perform the callback Thread callerbacker = new Thread(new Runnable() < @Override public void run() < try < // block until the running thread is done runner.join(); ((CallbackRunnable)r).callback(); >catch ( InterruptedException e ) < // someone doesn't want us running. ok, maybe we give up. >> >); callerbacker.start(); > > > 

The other sort-of obvious thing to add to your CallbackRunnable interface is a means to handle any exceptions, so maybe put a public void uncaughtException(Throwable e); line in there and in your executor, install a Thread.UncaughtExceptionHandler to send you to that interface method.

But doing all that really starts to smell like java.util.concurrent.Callable . You should really look at using java.util.concurrent if your project permits it.

Is it possible to check on which processor a thread is running in JAVA?, Is it possible to check on which processor a thread was running? Not sure about VisualVM, but you can get OS thread IDs for java threads

Java Examples — Thread completion

Problem Description

How to check a thread has stopped or not ?

Solution

Following example demonstrates how to check a thread has stop or not by checking with isAlive() method.

public class Main < public static void main(String[] argv)throws Exception < Thread thread = new MyThread(); thread.start(); if (thread.isAlive()) < System.out.println("Thread has not finished"); >else < System.out.println("Finished"); >long delayMillis = 5000; thread.join(delayMillis); if (thread.isAlive()) < System.out.println("thread has not finished"); >else < System.out.println("Finished"); >thread.join(); > > class MyThread extends Thread < boolean stop = false; public void run() < while (true) < if (stop) < return; >> > >

Result

The above code sample will produce the following result.

Thread has not finished Finished

How to check if thread is running or waiting in android, if(pause == true) rc.onresume();. out of my Runnable class it seems doesn’t work and my condition works how can i check when my thread is

How to check if a thread is running?

you can check Thread.isAlive() method.

It tests if this thread is alive. A thread is alive if it has been started and has not yet died.

I will rather advice to use a Future in such cases. Have your code as a FutureTask . Using Future.isDone will tell you if the Future is completed or not. And if yes, will also return you the value.

The good part is that you can use the same thread to execute multiple blocks of code as Future.

Runnable myRunnable; Thread t = new Thread(myRunnable); 
Future future = new FutureTask(myRunnable); ExecutorService ex= Executors.newFixedThreadPool(1); ex.submit(future); 

future.isDone will give you your desired. You can keep reusing ex

I have used this, and its working fine

if (thread.getState() == Thread.State.NEW)

Check if a Thread has started in Python, Initially, an event is set to 0. If the event is unset and a thread waits on the event, it will block (i.e., go to sleep) until the event gets

Источник

Оцените статью