Running Java threads sequentially

How will you execute three threads sequentially? E.g. Thread1, Thread2, Thread3. It is not possible to pass a link from one thread to another and call from the run () method.

So, the code should look like this:

Thread1.start(); Thread2.start(); Thread3.start(); 

and out should be

  Printing Thread1 Printing Thread2 Printing Thread3 

This can be done using ThreadPoolExecutor and using a blocking queue, but even this is not an acceptable answer.

+9
source share
13 answers

Use ExecutorService in java.util.concurrent package. More precisely, use Executors.newSingleThreadExecutor();

+10
source

You can use Executors.newSingleThreadExecutor () , but, strictly speaking, this only starts one Thread , so the expected solution is not expected.

The simplest solution using only the Thread class:

 Thread1.start(); Thread1.join(); Thread2.start(); Thread2.join(); Thread3.start(); Thread3.join(); 

(for clarity, I excluded exception handling, Thread.join() may throw an InterruptedException )

+15
source

The simplest answer:

 Thread1.run(); Thread2.run(); Thread3.run(); 

The problem with unrealistic questions is that they often have a non-informative answer .;)

The whole point of having threads is to run them at the same time. If you do not, do not use threads.

You could say that; you cannot call the run () method, in which case you cannot use ThreadPoolExecutor because it calls the run () method for you. that is what submit () does in the end.

EDIT: The results are completely deterministic because there is the fact that the involved thread is non-religious.

 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(); } 

Print

 A: 0 A: 1 .. deleted .. C: 98 C: 99 

as was expected.

+10
source

Since this is an interview question, they seek specific knowledge and not the answer β€œwell, obviously, it’s better to do so.” It also seems that they are likely to choose the solution after the solution until they get the answer they want.

Odds are what they want to see if you can implement cross-thread communications yourself. But they don’t want you to do this easily (references to the literature are available). Otherwise, you can just do thread.join() .

So, all three threads capture some bit of shared memory (synchronized static class). Ask each thread to check public static int nextThread() . After successfully comparing that they are the next thread, they should do their job and update the public static setNextThread(int value) with the value of the next thread to be processed.

The key is to do this in a thread-safe manner; however, if you can guarantee unique thread identifiers and make sure that none of the two streams has the same identifier, you can (with careful encoding) even do this without synchronization.

+4
source

If this were not related to the various methods of invoking these threads, theoretically they should use to acquire a common sempahore and release it upon completion of printing.
JDK has a built-in semaphore .

+4
source

Themes can be executed sequentially using the ExecutorService. Find an example below.

 public class SeqThread { public static void main(String[] arg) { new SeqThread().execute(); } public void execute() { try { ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(R); executor.submit(R2); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Runnable R = new Runnable() { @Override public void run() { // TODO Auto-generated method stub for(int i=0;i<10;i++) { System.out.println("In Thread One "+i); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; Runnable R2 = new Runnable() { @Override public void run() { // TODO Auto-generated method stub for(int i=0;i<10;i++) { System.out.println("In Thread Two="+i); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; } 
+4
source

Forcing threads to execute in an orderly manner, like destroying the concept of multithreading itself, more like running a single-threaded program. As an interview question, everything is in order. Here is a program that checks logic not with 4, but with 50 threads -

 public class Outer { private Thread[] jobs; private String[] names; private int indx; public Outer(int numOfThreads) { jobs = new Thread[numOfThreads]; names = new String[numOfThreads]; indx = numOfThreads - 1; } class Inner implements Runnable { public void run() { while (true) { if (names[indx].equals(Thread.currentThread().getName())) { indx--; break; } else { try { Thread.sleep(20); } catch(InterruptedException ie) {} } } // now current thread will join behind the previous one.. if (indx >= 0) try { jobs[indx].join(); } catch(InterruptedException ie) {} /***** YOUR ACTUAL CODE GOES FROM HERE *****/ // at last check is it working ? System.out.println(Thread.currentThread().getName()); } } public void f() { Inner target = new Inner(); // initializing all threads.. for (int i = 0; i < jobs.length; jobs[i++] = new Thread(target)); for (int i = 0; i < names.length; names[i] = jobs[i++].getName()); // checking name of threads.. for (int i = 0; i < names.length; System.out.println(names[i++])); System.out.println(); // now we start all threads.. for (int i = 0; i < jobs.length; jobs[i++].start()); } public static void main(String[] args) { new Outer(50).f(); // testing logic not with 4 but 50 threads.. } } 
+2
source

You can find everything: http://download.oracle.com/javase/tutorial/essential/concurrency/index.html

It is especially read about notifications and synchronization between flows.

PS And remember, even if you pass the interview, you still have to work! :)

(Well, I will give a few tips: look at the description of methods such as Object.wait() and Object.notifyAll() , this is the simplest, but also very useful mechanism)

+1
source

newSingleThreadExecutor. A single-threaded worker creates one workflow for processing tasks, replacing it if it unexpectedly dies. It is guaranteed that tasks will be processed sequentially in accordance with the order specified in the task queue (FIFO, LIFO, priority order).

+1
source

This can be a trick question. They may not want to hear a solution to this particular problem, but they want you to contact the source of the problem and come up with a better solution.

0
source

I used the basic communication model, and it could be simplified. Say you have 3 threads, one prints 0, the second prints an odd number, and the third prints an even number. 01 02 03 04 05 ....

 public class app{ int status=0; public static void main(String[] args) throws InterruptedException{ app obj = new app(); Thread t1 = new Thread(new print(obj,0)); Thread t2 = new Thread(new print(obj,1)); Thread t3 = new Thread(new print(obj,2)); t1.start();t2.start();t3.start(); } } class print implements Runnable{ app obj; int a; public print(app obj, int a) { this.obj=obj; this.a=a; } @Override public void run() { try{ if(a==0){ synchronized(obj){ for (int i = 0; i < 21; i++) { while(obj.status!=0 && obj.status!=3){ obj.wait(); } System.out.print(0); if(obj.status==0)//even sets status to 0 so next one is odd obj.status=1; else//odd sets status to 3 so next one is even obj.status=2; obj.notifyAll(); } } } else if(a%2!=0){ synchronized (obj) { for (int i = 0; i < 11; i++) { while(obj.status!=1){ obj.wait(); } System.out.print(a); a+=2; obj.status=3; //3 decides 0 came after odd, so next one //after zero is even obj.notifyAll(); } } } else{ synchronized (obj) { for (int i = 0; i < 11; i++) { while(obj.status!=2){ obj.wait(); } System.out.print(a); a+=2; obj.status=0; obj.notifyAll(); } } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 
0
source

I'm not sure if I fully understood the question, but it seems like a situation where we want to print topics in order. One example is printing a value using streams in the following sequence:

Thread - 0 pin: 1

Thread - 1 outlet: 2

Thread - 2 outlets: 3

Thread - 0 pin: 4

Thread - 1 outlet: 5

Thread - 2 outputs: 6, etc.

If this is a requirement, then we can write a general solution for n threads, where each thread will wait for its turn (using a common object for which it will try to obtain a lock).

 class ResourceLock { private volatile int currentThreadId; private final int totalThreads; public ResourceLock(int threadsCount) { this.currentThreadId = 0; this.totalThreads = threadsCount; } public void assignTokenToNextThread(int currentThreadNum) { this.currentThreadId = (currentThreadNum + 1) % totalThreads; } public int getCurrentThreadId() { return currentThreadId; } } 

Now the worker thread will do its job and will use an instance of the above class to lock:

 class Worker extends Thread { private final ResourceLock resourceLock; private final int threadId; // id of this thread private final AtomicInteger counter; // counter shared by all threads, will print number in sequence. private volatile boolean running = true; // flag to stop this thread when necessary public Worker(ResourceLock resourceLock, int threadNumber, AtomicInteger counter) { this.resourceLock = resourceLock; this.threadId = threadNumber; this.counter = counter; } @Override public void run() { while (running) { try { synchronized (resourceLock) { while (resourceLock.getCurrentThreadId() != this.threadId) { resourceLock.wait(); } System.out.println("Thread:" + threadId + " value: " + counter.incrementAndGet()); Thread.sleep(1000); resourceLock.assignTokenToNextThread(this.threadId); resourceLock.notifyAll(); } } catch (Exception e) { System.out.println("Exception: " + e); } } } public void shutdown() { running = false; } } 

And it can be checked as:

 public static void main(String[] args) throws InterruptedException { final int threadsCount = 3; final ResourceLock lock = new ResourceLock(threadsCount); Worker[] threads = new Worker[threadsCount]; final AtomicInteger counter = new AtomicInteger(0); for(int i=0; i<threadsCount; i++) { threads[i] = new Worker(lock, i, counter); threads[i].start(); } Thread.sleep(20000); System.out.println("Will try to shutdown now..."); for(Worker worker: threads) { worker.shutdown(); } } 
0
source
 public static void main(String[] args)throws InterruptedException { MyRunnable r = new MyRunnable(); Thread t1 = new Thread(r,"A"); Thread t2 = new Thread(r,"B"); Thread t3 = new Thread(r,"C"); t1.start(); Thread.sleep(1000); t2.start(); Thread.sleep(1000); t3.start(); } 
-2
source

All Articles