Creating and naming multiple, simultaneous threads with a for loop - java

Is there a way to create multiple threads that run simultaneously with a for loop? Consider this example:
for(int i = 1; i<=36; i++) {
if(new Random().nextInt(2)==0){
ActionThread nr = new ActionThread();
}
}
I don't want the threads to be killed after completion of the if statement. The end of each thread is randomly determined in the ActionThread class itself. Also, how do I name the threads automatically? For example, instead of nr, the first thread should be named nr1, the second nr2, the third nr3, and so on.

I'm assuming that ActionThread is some custom class that you have created that extends Thread.
I don't want the threads to be killed after completion of the if statement.
They won't be. However, it doesn't look like you have started them yet. Read the javadocs for Thread. Read the material at the top, then look at the start() and run() methods.
If you don't start a thread ... nothing happens.
Also, if you want some other part of your application to be able to "do things" to the threads once they have been created, you should replace the nr local variable with a data structure that the the rest of the application can get at; e.g. a list or an array.
(It is also possible to find extant threads via the ThreadGroup tree, but it is complicated.)
Also, how do I name the threads automatically?
Call Thread.setName(), or pass the thread name to the (relevant) Thread constructor. For example:
nr.setName("thr" + i);
Or you could even make your ActionThread set its own name in the constructor.
I should also point out that is is generally considered to be a bad idea to create subclasses of Thread. It is better to put your thread logic into a custom Runnable class, then create and pass a Runnable instance as a Thread construct argument. Like this:
public class MyRunnable implements Runnable {
#Override
public void run() {
// thread logic goes here
}
}
Thread th = new Thread(new MyRunnable());
th.start();
If you want to pass parameters to the thread logic, add a constructor to your runnable class with some arguments, and provide them when you instantiate the runnable.
Why do it this way? Because it allows you to easily change your code to use a thread loop or executor or some such.

public static void main(String[] a) {
List<ActionThread> threads = new ArrayList<>();
for (int i = 1; i <= 36; i++) {
if (new Random().nextInt(2) == 0) { // no idea why you have put this
// but seems unecessary
ActionThread thread = new ActionThread();
threads.add(thread);
thread.start();
}
}
}
class ActionThread extends Thread {
#Override
public void run() {
// Write what to do in Thread here
}
}
Once the list of ActionThread is there you have handle to all the Threads that you have created. using threads.get(index). From question its appears that by name you meant handle to Thread instance

For automatic naming, may be use static field (counter) in ActionThread and increment him in the constructor, before generate thread name.
class ActionThread extend Thread {
private static int id = 0;
ActionThread() {
setName(String.format("n%d", ++id);
}
}

Related

Finding the Names of active threads inside a threadpool : ExecutorService in java

So I am running an executor service and I would like to know the Names or the threadIDs of all the currently active/idle threads.
ExecutorService service = Executors.newCachedThreadPool(ThreadFactory threadFactory)
I do not need to know the count, but the actual names/IDs of all the active threads in my executor service. I need to identify the threads in any manner because I plan on implementing my own ThreadFactory with an appropriate naming convention.
For example, if my active threads are T0,T1,T3, my threadfactory would name the next thread as T2. But I can't find a way to get information about the active Threads.
How can I do that?
PS : Any other methods would also be appreciated. For example, lets say I am fine with having threads with names from T0 to T50. I just want my current threadfactory to assign any name from T0 to T50 such that a thread with the same name is not currently active or idle.
I was so free to create you a sample, of something I would've done. I couldn't really test it though:
public class CachingThreadFactory implements ThreadFactory{
// amount of active threads at max
private static final int THREAD_POOL_MAX_SIZE = 8;
// interval in milliseconds of the clean up task
private static final int CLEAN_UP_INTERVAL = 2000;
// the actual cache
private final Thread[] cachedThreads = new Thread[THREAD_POOL_MAX_SIZE];
// clean up task definition
{
new Timer().scheduleAtFixedRate(new CleanUpTask(), 0, CLEAN_UP_INTERVAL);
}
#Override
public synchronized Thread newThread(Runnable r){
for(int i = 0; i < cachedThreads.length; i++){
if(cachedThreads[i] == null){
return cachedThreads[i] = new Thread(r, "T" + i);
}
}
return null;
}
private final class CleanUpTask extends TimerTask{
#Override
public void run(){
synchronized(CachingThreadFactory.this){
for(int i = 0; i < cachedThreads.length; i++){
final Thread thread = cachedThreads[i];
if(thread != null && !thread.isAlive()){
cachedThreads[i] = null; // unset
}
}
}
}
}
}
This Factory caches every Thread it creates in an array. Then it runs a cleanUpTask asynchronly which checks if the threads in the array (if any) are still alive. If not they are removed.
The newThread method iterates through the cache, to find an index which is not yet taken, and then uses that index to create the name of that Thread. If no place is free it just returns null.
This class is probably thread safe. But I haven't really tested it. The synchronized-statements should prevent the interference between the cleanUp-Task and the newThread method. But any other action may disturb the whole thing.
call instead
Executors.newCachedThreadPool(ThreadFactory threadFactory)
and pass your implementation of ThreadFactory. There you can manage thread names at thread creation time.
Connect to your running program via jconsole or jvisual vm. It will give you all the running threads and their names.

Java lambdas LinkedBlockingQueue unexpected behaviour

I am trying to add elements in t linkedBlockingQueue from a thread, created using lambda, When I poll the queue using the take method, I can see that the last values entered from the thread overrides the previous values.
Following is the code :-
public List<EntryBarricade> entryBarricades() {
List<EntryBarricade> entryBarricades = new ArrayList<>();
EntryBarricade entryBarricade;
Runnable runnable;
for (int i =0;i<=1;i++) {
EntryRequest entryRequest = new EntryRequest("Barricade-"+i);
runnable = new Runnable() {
#Override
public void run() {
ExecutorService entryGate1 = Executors.newSingleThreadExecutor();
for (int j =0;j<=1;j++) {
entryGate1.submit(() -> {
entryRequest.setVehicleId(Thread.currentThread().getName()
+ " " + new Double(Math.random()));
entryRequestQueuingService.Queue(entryRequest);
});
}
}
};
entryBarricade = new EntryBarricade("Barricade-"+i, runnable);
entryBarricades.add(entryBarricade);
}
return entryBarricades;
}
After polling the queue, I get the following:-
Request{barricadeId='Barricade-0', vehicleId='pool-2-thread-1 0.9091480024731418'}
Request{barricadeId='Barricade-0', vehicleId='pool-2-thread-1 0.05687657229049259'}
Request{barricadeId='Barricade-1', vehicleId='pool-3-thread-1 0.7978996055410615'}
Request{barricadeId='Barricade-1', vehicleId='pool-3-thread-1 0.2734508504023724'}
Request{barricadeId='Barricade-0', vehicleId='pool-2-thread-1 0.05687657229049259'}
Request{barricadeId='Barricade-0', vehicleId='pool-2-thread-1 0.05687657229049259'}
Request{barricadeId='Barricade-1', vehicleId='pool-3-thread-1 0.2734508504023724'}
Request{barricadeId='Barricade-1', vehicleId='pool-3-thread-1 0.2734508504023724'}
I am not sure what is happening.
Can some one please explain this behaviour ??
Thanks,
Amar
I assume the problem here: your entryRequest is created in each iteration of your loop (in the main thread). So when the thread pool executor comes to call your lamdba it might have changed already. You have absolute no control who access when this variable.
Instead of constructing an anonymous Runnable class better write your own implementation of Runnable, pass the entryRequest as parameter to it (e.g by constructor or setter) and let the run method then operate on this passed variable. This ensures that each thread operates on its own entryRequest instance.

Can this reference in run() refer to Thread object when implementing Runnable?

Sorry if the question is unclear
I am making a simple multithread program that has a linked list to store all thread created except the main thread. Then I want to send some signal to terminate the main thread but only when all other threads have closed and I intend to do this by making that when the thread close, it will remove itself from linked list then the main thread will check if that list size == null or not
here is my code
public class MainProgram {
//some global static variable
static List<Thread> threadList = new LinkedList<Thread>();
public void main() throws IOException {
ServerSocket serverSocket;
serverSocket = new ServerSocket(1234);
while(true){
if(Shutdown_Handler.shutdown==true){
//wait for all other thread close/terminate
return
}
Socket s = serverSocket.accept();
ClientThread x = new ClientThread(s);
Thread y = new Thread(x);
threadList.add(y);
y.start();
}
}
}
when Shutdown_Handler.shutdown==true the main will check the threadList if it is null. The problem is I don't know how to make the thread remove itself from the list. As what I have searched, for normal object, I can create method like this
public class someObject {
public static void delete(){
if(list.size = null) return;
list.remove(this);
}
}
However, in case of thread, the Class implement Runnable so this reference is to the object but not the thread stored in the list
I would recommend using a HashMap instead of a List. The keys can be the Thread Name (e.g. Thread.getName()) and the values will be the Threads.
Map<String, Thread> threadMap = new HashMap<String, Thread>();
You should also create this Map as a synchronizedMap (using Collections.synchronizedMap(...))
Map<String, Thread> synchronizedMap = Collections.synchronizedMap(threadMap);
Now, whenever you construct a Thread, you pass this HashMap into its constructor and the Thread can hold a reference to it. Therefore, when the Thread is about to terminate it can remove itself from the HashMap by using its own Thread name as the key to remove.
Assuming that ClientThread is a Runnable, the basic code is:
public class ClientThread implements Runnable {
public void run() {
// do stuff
MainProgram.threadList.remove(Thread.currentThread());
}
}
However this has a couple of problems:
There are going to be multiple threads performing operations on a list without proper synchronization. That is incorrect, and you are liable to get intermittent failures if you do this.
Unless run() removes the thread from the list in a finally block, a thread that terminates abnormally is liable to not get removed.
It is bad design to use a global static. And worse design to expose it as a bare (non-private) variable.
A HashSet<Thread> would be more efficient if the number of threads is liable to be large.

Particular Thread Count

I want to know how many active threads are there for a particular Thread class.
Lets say I have a class T which extends thread. In some other class (Ex: Demo) , I want to get the thread count for the T class Thread. I do know Thread.activeCount() method but it will get the count for a thread group. It does not server my need here. Lets say I have T1 and T2 classes which extends thread and In the Demo class I want to get How many T2 active threads are there.
How should I achieve this? Any Ideas??
PS: I don't have source code for the Class T1 and T2.
Thanks for the help.
You can use Thread.enumerate():
public int countThreadsOfClass(Class<? extends Thread> clazz) {
Thread[] tarray = new Thread[Thread.activeCount()];
Thread.enumerate(tarray);
int count = 0;
for(Thread t : tarray) {
if(clazz.isInstance(t))
count++;
}
return count;
}
Your Thread (or Runnable) subclass can maintain a static active count. Increment when run() starts, decrement when run() ends (in a finally block).
Make sure the increment/decrement is done in a multithread secure way.
You could implement ThreadFactory to construct the custom Thread classes and supply a ThreadGroup instance to get the counts from. By using ThreadFactory, each instance could contain its own ThreadGroup, making counts accessible based on the factory used.
Try to use ThreadPoolExecutor.
You can extend the ThreadPoolExecutor and counts the number of threads by calling getActiveCount().
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
private static int getThreadCount(){
int runningThread = 0;
for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getState()==Thread.State.RUNNABLE && t instanceof YourThreadClassName ) runningThread++;
System.out.println("Active threads : "+runningThread);
return runningThread;
}
Justreplace YourThreadClassName with your class that is extended by Thread.

Should you synchronize the run method? Why or why not?

I have always thought that synchronizing the run method in a java class which implements Runnable is redundant. I am trying to figure out why people do this:
public class ThreadedClass implements Runnable{
//other stuff
public synchronized void run(){
while(true)
//do some stuff in a thread
}
}
}
It seems redundant and unnecessary since they are obtaining the object's lock for another thread. Or rather, they are making explicit that only one thread has access to the run() method. But since its the run method, isn't it itself its own thread? Therefore, only it can access itself and it doesn't need a separate locking mechanism?
I found a suggestion online that by synchronizing the run method you could potentially create a de-facto thread queue for instance by doing this:
public void createThreadQueue(){
ThreadedClass a = new ThreadedClass();
new Thread(a, "First one").start();
new Thread(a, "Second one, waiting on the first one").start();
new Thread(a, "Third one, waiting on the other two...").start();
}
I would never do that personally, but it lends to the question of why anyone would synchronize the run method. Any ideas why or why not one should synchronize the run method?
Synchronizing the run() method of a Runnable is completely pointless unless you want to share the Runnable among multiple threads and you want to sequentialize the execution of those threads. Which is basically a contradiction in terms.
There is in theory another much more complicated scenario in which you might want to synchronize the run() method, which again involves sharing the Runnable among multiple threads but also makes use of wait() and notify(). I've never encountered it in 21+ years of Java.
There is 1 advantage to using synchronized void blah() over void blah() { synchronized(this) { and that is your resulting bytecode will be 1 byte shorter, since the synchronization will be part of the method signature instead of an operation by itself. This may influence the chance to inline the method by the JIT compiler. Other than that there is no difference.
The best option is to use an internal private final Object lock = new Object() to prevent someone from potentially locking your monitor. It achieves the same result without the downside of the evil outside locking. You do have that extra byte, but it rarely makes a difference.
So I would say no, don't use the synchronized keyword in the signature. Instead, use something like
public class ThreadedClass implements Runnable{
private final Object lock = new Object();
public void run(){
synchronized(lock) {
while(true)
//do some stuff in a thread
}
}
}
}
Edit in response to comment:
Consider what synchronization does: it prevents other threads from entering the same code block. So imagine you have a class like the one below. Let's say the current size is 10. Someone tries to perform an add and it forces a resize of the backing array. While they're in the middle of resizing the array, someone calls a makeExactSize(5) on a different thread. Now all of a sudden you're trying to access data[6] and it bombs out on you. Synchronization is supposed to prevent that from happening. In multithreaded programs you simply NEED synchronization.
class Stack {
int[] data = new int[10];
int pos = 0;
void add(int inc) {
if(pos == data.length) {
int[] tmp = new int[pos*2];
for(int i = 0; i < pos; i++) tmp[i] = data[i];
data = tmp;
}
data[pos++] = inc;
}
int remove() {
return data[pos--];
}
void makeExactSize(int size) {
int[] tmp = new int[size];
for(int i = 0; i < size; i++) tmp[i] = data[i];
data = tmp;
}
}
Why? Minimal extra safety and I don't see any plausible scenario where it would make a difference.
Why not? It's not standard. If you are coding as part of a team, when some other member sees your synchronized run he'll probably waste 30 minutes trying to figure out what is so special either with your run or with the framework you are using to run the Runnable's.
From my experience, it's not useful to add "synchronized" keyword to run() method. If we need synchronize multiple threads, or we need a thread-safe queue, we can use more appropriate components, such as ConcurrentLinkedQueue.
Well you could theoretically call the run method itself without problem (after all it is public). But that doesn't mean one should do it. So basically there's no reason to do this, apart from adding negligible overhead to the thread calling run(). Well except if you use the instance multiple times calling new Thread - although I'm a) not sure that's legal with the threading API and b) seems completely useless.
Also your createThreadQueue doesn't work. synchronized on a non-static method synchronizes on the instance object (ie this), so all three threads will run in parallel.
Go through the code comments and uncomment and run the different blocks to clearly see the difference, note synchronization will have a difference only if the same runnable instance is used, if each thread started gets a new runnable it won't make any difference.
class Kat{
public static void main(String... args){
Thread t1;
// MyUsualRunnable is usual stuff, only this will allow concurrency
MyUsualRunnable m0 = new MyUsualRunnable();
for(int i = 0; i < 5; i++){
t1 = new Thread(m0);//*imp* here all threads created are passed the same runnable instance
t1.start();
}
// run() method is synchronized , concurrency killed
// uncomment below block and run to see the difference
MySynchRunnable1 m1 = new MySynchRunnable1();
for(int i = 0; i < 5; i++){
t1 = new Thread(m1);//*imp* here all threads created are passed the same runnable instance, m1
// if new insances of runnable above were created for each loop then synchronizing will have no effect
t1.start();
}
// run() method has synchronized block which lock on runnable instance , concurrency killed
// uncomment below block and run to see the difference
/*
MySynchRunnable2 m2 = new MySynchRunnable2();
for(int i = 0; i < 5; i++){
// if new insances of runnable above were created for each loop then synchronizing will have no effect
t1 = new Thread(m2);//*imp* here all threads created are passed the same runnable instance, m2
t1.start();
}*/
}
}
class MyUsualRunnable implements Runnable{
#Override
public void run(){
try {Thread.sleep(1000);} catch (InterruptedException e) {}
}
}
class MySynchRunnable1 implements Runnable{
// this is implicit synchronization
//on the runnable instance as the run()
// method is synchronized
#Override
public synchronized void run(){
try {Thread.sleep(1000);} catch (InterruptedException e) {}
}
}
class MySynchRunnable2 implements Runnable{
// this is explicit synchronization
//on the runnable instance
//inside the synchronized block
// MySynchRunnable2 is totally equivalent to MySynchRunnable1
// usually we never synchronize on this or synchronize the run() method
#Override
public void run(){
synchronized(this){
try {Thread.sleep(1000);} catch (InterruptedException e) {}
}
}
}

Categories

Resources