Barclays Capital Interview Question
Senior Software Development EngineersCountry: United States
Here is the solution...
public class InsteadJoin {
public Thread createThread(String name){
Thread t = new Thread(name){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
return t;
}
public void myJoin(Thread t){
while(t.isAlive()){
}
}
public static void main(String[] args) {
InsteadJoin ij = new InsteadJoin();
System.out.println("Start");
Thread t = ij.createThread("A");
Thread t1 = ij.createThread("B");
Thread t2 = ij.createThread("C");
t.start();
ij.myJoin(t);
t1.start();
ij.myJoin(t1);
t2.start();
ij.myJoin(t2);
System.out.println("Done");
}
}
The simplest answer is
Thread1.run();
Thread2.run();
Thread3.run();
The problem with unrealistic questions is they often have an uninformative answer. ;)
The whole point of having threads is to run them concurrently. If you are not doing that at all, don't use threads.
You might say that; you cannot call the run() method, in which case you cannot use ThreadPoolExecutor because it calls the run() method for you. i.e. thats what submit() eventually does.
EDIT: The results are completely deterministic, becaus ethe fact that there is a Thread involved is irrelivent.
static class PrintThread extends Thread {
public PrintThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(getName() + ": " + i);
}
}
public static void main(String args[]) {
Thread thread1 = new PrintThread("A");
Thread thread2 = new PrintThread("B");
Thread thread3 = new PrintThread("C");
thread1.run();
thread2.run();
thread3.run();
}
Prints
A: 0
A: 1
.. deleted ..
C: 98
C: 99
can be done by giving threads their sequence and when the running value equals that value then the thread is allowed to run
as below
class resource
{
private int sequence;
public resource(int i) {
this.sequence=i;
}
public int getSequence() {
return sequence;
}
public synchronized void incementSequence()
{
sequence++;
}
}
class sequence implements Runnable
{
int sequence;
resource obj;
public sequence(int i,resource obj) {
this.sequence=i;
this.obj=obj;
}
public void run() {
synchronized(obj)
{
while(obj.getSequence()!=sequence)
{
try {
obj.wait();
} catch (InterruptedException ex) {
Logger.getLogger(sequence.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("my processing is done with sequence->"+sequence);
obj.incementSequence();
obj.notifyAll();
}
}
}
public class sequenceRunning {
public static void main(String args[])
{
sequence obj[]=new sequence[3];
resource objresource=new resource(1);
for(int i=0;i<3;i++)
{
obj[i]=new sequence(i+1,objresource);
Thread runThread=new Thread(obj[i]);
runThread.start();
}
}
}
Perhaps the OP meant to say that the 3 thread can be started in any order.
R implements Runnable {
private Semaphore s1;
private Semaphore s2;
public R(Semaphore s1, Semaphore s2) {
this.s1 = s1;
this.s2 = s2;
}
public void run() {
// Wait until s1 is released
if (s1 != null)
s1.aquire();
// Do some work here
if (s1 != null)
s1.release();
// Allow the thread that is waiting for s2 to proceed
if (s2 != null)
s2.release();
}
public static void main(...) {
Semaphore s2 = new Semaphore(0);
Semaphore s3 = new Semaphore(0);
Thread t1 = new Thread(new R(null, s2));
Thread t2 = new Thread(new R(s2, s3));
Thread t3 = new Thread(new R(s3, null));
t1.start();
t2.start();
t3.start();
}
}
You may find this solution bit expensive but condition variable can be used to synchronize these threads sequentially
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mt = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void * th3_impl(void *)
{
pthread_mutex_lock(&mt);
printf("Inside third thread\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mt);
}
void * th2_impl(void *)
{
pthread_mutex_lock(&mt);
printf("Inside second thread\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mt);
}
void * th1_impl(void *)
{
pthread_mutex_lock(&mt);
printf("Inside first thread\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mt);
}
int main()
{
pthread_t th1,th2,th3;
pthread_mutex_lock(&mt);
pthread_create(&th1, NULL, &th1_impl, NULL);
pthread_cond_wait(&cond,&mt);
pthread_mutex_unlock(&mt);
pthread_mutex_lock(&mt);
pthread_create(&th2, NULL, &th2_impl, NULL);
pthread_cond_wait(&cond,&mt);
pthread_mutex_unlock(&mt);
pthread_mutex_lock(&mt);
pthread_create(&th3, NULL, &th3_impl, NULL);
pthread_cond_wait(&cond,&mt);
pthread_mutex_unlock(&mt);
}
It should be possible to use a FIFO mutex as well to solve this problem. It allows the mutex to be passed to next thread in queue.
Where to use :
Assume two threads T1 and T2 are trying to execute a critical section. Both don't have much to do outside this critical section and hold locks for a good amount of time. So, T1 may lock, execute and unlock and signal T2 for wakeup. But before T2 could wakeup and acquire lock, T1 reacquires lock and execute. In this way, T2 may have to wait a very long time before it actually gets the lock or may be not.
How it works / How to implement :
Have a mutex to lock on. Initialize Thread Specific Data (TSD) for each thread to a node containing thread id and semaphore. Also, have two variables - owned (TRUE or FALSE or -1), owner (owner thread id). In addition, keep a waiters queue and a pointer waiterLast pointing to last node in waiters queue.
lock operation :
node = get_thread_specific_data(node_key);
lock(mutex);
if(!owned)
{
owned = true;
owner = self;
return success;
}
node->next = nullptr;
if(waiters_queue == null) waiters_queue = node;
else waiters_last->next = node;
waiters_last = node;
unlock(mutex);
sem_wait(node->semaphore);
lock(mutex);
if(owned != -1) abort();
owned = true;
owner = self;
waiters_queue = waiters_queue->next;
unlock(mutex);
unlock operation :
lock(mutex);
owner = null;
if(waiters_queue == null)
{
owned = false;
return success;
}
owned = -1;
sem_post(waiters_queue->semaphore);
unlock(mutex);
Synchronizing threads without using join method is possible. If you are aware of wait(), notify() and notifyAll() methods, so can might be aware of the use of this methods. You can synchronize you thread with the help of these important methods. If you want to see good real implementation of this you can visit below given this link where you can see good example of this.
somanyword.com/2013/11/how-to-make-threads-in-sequence-execution-without-using-join/
#include<pthread.h>
#include<stdio.h>
int num_threads=3;
int state=0;
pthread_cond_t cond;
pthread_mutex_t mutex;
void* threadA(void* args) {
int i;
for(i=0; i<5; i++){
pthread_mutex_lock(&mutex);
while(state == 1 || state == 2) pthread_cond_wait(&cond,&mutex);
printf("Thread A\n");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
void* threadB(void* args) {
int i;
for(i=0; i<5; i++){
pthread_mutex_lock(&mutex);
while(state == 0 || state == 2)pthread_cond_wait(&cond,&mutex);
printf("Thread B\n");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
void* threadC(void* args) {
int i;
for(i=0; i<5; i++){
pthread_mutex_lock(&mutex);
while(state == 1 || state == 0) pthread_cond_wait(&cond,&mutex);
printf("Thread C\n\n");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main() {
pthread_t tid[3];
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex,NULL);
pthread_create(&tid[0],NULL,threadA,NULL);
pthread_create(&tid[1],NULL,threadB,NULL);
pthread_create(&tid[2],NULL,threadC,NULL);
return 0;
}
1. If you know the exact sequence then simply invoke run method sequentially without creating Thread.
2. If you know the exact sequence and Threads have to be created in anyway then we can go for setting the priorities according to the sequence.
3. And if the sequence is not known and Threads have to be created then simply use synchronized block or lock method of ReentrantLock Class inside run() method.
Don't see the point in the question.
- EK MACHCHAR May 04, 2013call run of B in run of A and so on. Seems a warm up question.