Home > Programming > Series About Java Concurrency – Pt. 5

Series About Java Concurrency – Pt. 5

After quite some time, here is a concurrency related puzzle once again: Take a look at the following program and try to predict its output:

package com.wordpress.mlangc.concurrent;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadNoMore extends Thread
    private static final int N_THREADS = 16;
    private static final AtomicInteger threadsStarted = new AtomicInteger();
    private final long ctorThreadId = Thread.currentThread().getId();
    public synchronized void start()
        if(ctorThreadId != Thread.currentThread().getId())
    public static void main(String[] args) throws InterruptedException
        Thread[] threads = new Thread[N_THREADS];
        for(int i = 0; i != N_THREADS; ++i)
            threads[i] = new ThreadNoMore();
        for(Thread th : threads)
        for(Thread th : threads)
        System.out.println("threadsStarted: " + threadsStarted);

The solution, together with a detailed explanation will be available soon.

Categories: Programming Tags: , ,
  1. February 13, 2013 at 16:44

    This code is misleading, as the start() override never calls super.start(). So no thread is ever started really. The condition in start() is always false as the calling thread is always the creating thread. join() also never actually blocks (as no thread was started). The program always prints 0.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: