I’m a beginner in java and I’m looking to learn more about it, so I’d like to know how to know if the threads are running?

Asked

Viewed 38 times

-2

import com.sun.corba.se.spi.orbutil.threadpool.ThreadPool;



public class Game {
private boolean isAlive;
public static void main(String[] args) {
    if(args.length !=2){
        System.out.println("teste de thread");
        System.out.println("testando");
    }
    
    int numTasks = Integer.parseInt(args[0]);
    int numThreads = Integer.parseInt(args[1]);
    
   
    ThreadPool threadPool = new ThreadPool(numThreads);
    
   
    for(int i =0; i<numTasks; i++){
        threadPool.runTask(createTask(i));
    }
}
    private static Runnable createTask(final int taskID){
        return new Runnable(){
            public void run(){
                System.out.println("task "+taskID+": start");
                try{
                Thread.sleep(500);
            }catch(InterruptedException rx){}
                System.out.println("task "+taskID+": end");
            }
        
        }
    
    }

}

  • Here has some options (not tested). But in your case, do not just see if the messages "task start" and "task end" are showing?

  • In this case the "task end" message will never appear because the threads are not interrupted. Interrupting a thread is an action that needs to be done explicitly and has nothing to do with the normal thread ending.

1 answer

0

The class Thread is an abstraction of Java for operating system threads.

The class typically used to create a thread pool is wrong. It wouldn’t be ThreadPool of the CORBA package, for example a Executor of the Java competition package.

Even so, it will not give access to the individual threads of the pool (tank) of threads, but rather to an API for scheduling tasks to be performed by the threads of this pool, in a closed way, without control of the individual threads.

To know if a specific thread is running a shape is to instantiate it and store its reference in a variable. Example:

Thread thread = new Thread(runnable);
thread.start();

if (thread.isAlive()) {
    System.out.println("A thread está rodando.");
}

To learn more about threads study material about Threads of Java (no Java Tutorials Oracle has, in English), the resources of competition control, and later on the Executors to create thread pools.

It is also worth studying threads from the point of view of the operating system. A possible starting point: What is a Thread? How It Works?

  • vlw Piovezan!!!

  • Do the [tour] to know how to thank.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.