praks5432
praks5432

Reputation: 7792

Prohibiting One Task when another is running

So let's say I'm creating and starting a bunch of threads in a for loop, that is being executed in the run method of a launcher thread. Let's also say that I want to be able to interrupt the launcher thread and all threads that the thread has created, and I do this through a button.

So something like this -

try{
            for(int i = 0; i < n;i++){

                Worker currThread = new Worker(someArgs);
                workerThreads.add(currThread);
                currThread.start();
            }
        } catch (InterruptedException e){
            e.printStackTrace();
        }

BUTTON-

public void actionPerformed(ActionEvent arg0) {

    List<Worker> threads = launchThread.getWorkerThreads();
        for(int i = 0; i < threads.size();i++){
            threads.get(i).interrupt();
        }
        launchThread.interrupt();

    }

Now, let's say that I want to make it so that the interrupts cannot occur at the same time as thread creation. I think a way to do this would be to construct a dummy object and put both pieces of code inside a lock

synchronized(dummyObject){
//thread creation or interruption code here (shown above) 
}

Will this way work? I ask because I'm not sure how to test to see if it will.

Upvotes: 0

Views: 43

Answers (2)

deprecated
deprecated

Reputation: 5252

The concept of synchronization remains the same however complicated are the underlying operations to be executed.

As you specified, there are two types of mutually exclusive tasks (thread creation and interruption). So locking is pretty much the canonical tool for the job.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360046

Start the threads separately from creating them.

for(int i = 0; i < n; i++) {
    Worker currThread = new Worker(someArgs);
    workerThreads.add(currThread);
}

// later
for (Worker w : workerThreads) {
    w.start();
}

If that's still not enough, your dummyObject synchronization should work just fine.

// You probably need to make this a (private final) field
Object lock = new Object();

// later
synchronized (lock) {
    for(int i = 0; i < n; i++) {
        Worker currThread = new Worker(someArgs);
        workerThreads.add(currThread);
        w.start();
    }
}

// later still
public void actionPerformed(ActionEvent arg0) {
    synchronized (lock) {
        // interruption code here
    }
}

Upvotes: 1

Related Questions