How to make two thread wait for each other outcome? - java

Here is my example code.
class A implements Runnable{
//stuff
Thread thr = new Thread(this);
boolean flag;
public void run()
{
while(true){
if(condition)flag = true;
}
}
}
class B implements Runnable{
//stuff
A a = new A();
Thread thr = new Thread(this);
public void run()
{
while(true){
//i ll do some thing here
if(a.flag == true)System.out.println("Kaboom");
}
}
public static void main(String[] args)
{
B b = new B();
}
}
So the thing is i start b before a and i want b to wait until a.flag == true to fire "Kaboom" and a.thr have to wait when b doing its work in run() method. I tried this but it doesnt work
class A implements Runnable{
//stuff
Thread thr = new Thread(this);
boolean flag;
public void run()
{
while(true){
if(condition)flag = true;
synchronized(B.class){
this.flag=true;
B.class.notifyAll();
}
}
}
}
class B implements Runnable{
//stuff
A a = new A();
Thread thr = new Thread(this);
public void run()
{
while(true){
synchronized(this){
while(a.flag!=true)
{
this.wait();
}}
}
}
public static void main(String[] args)
{
B b = new B();
}}
There must be a problem in my synchronized block but i dont know what.
This probably a stupid question but i'm just a beginner in JAVA and i dont really get those Thread stuff and how it work. Plz help me

I like your original approach of using wait / notifyAll to make the Thread doesn't use the CPU until the condition is met for it to resume running. Here's a solution that keeps this approach.
A few notes:
1 - Be careful when synchronizing on a class object. Unless you really want to synchronize the whole class, create an Object and use it as a lock.
2 - Use the volatile keyword to ensure that Java doesn't create a thread local version of the variable and that changes to it's value are instantly reflected to other threads.
public class Threads {
private final Object lock = new Object();
private volatile boolean flag;
class RunnableA implements Runnable {
private volatile boolean condition = false;
#Override
public void run() {
while (true) {
if (condition) {
if (!flag) {
synchronized (lock) {
System.out.println("Setting Flag to True");
flag = true;
lock.notifyAll();
}
}
} else {
System.out.println("Condition is False");
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
}
}
}
}
class RunnableB implements Runnable {
#Override
public void run() {
while (true) {
while (flag == false) {
synchronized (lock) {
if (flag == false) {
try {
lock.wait();
} catch (InterruptedException ex) {
}
}
}
}
System.out.println("Kaboom");
}
}
}
public void run() {
RunnableA runnableA = new RunnableA();
RunnableB runnableB = new RunnableB();
Thread t1 = new Thread(runnableA);
Thread t2 = new Thread(runnableB);
t1.start();
t2.start();
try {
Thread.sleep(5000L);
} catch (InterruptedException ex) {
}
runnableA.condition = true;
}
public static void main(String[] args) {
new Threads().run();
}
}

You created a Runnable but did not start it in a thread.
Proper one:
import java.lang.*;
import java.util.concurrent.atomic.*;
class A implements Runnable {
AtomicBoolean flag;
AtomicBoolean condition;
A() {
flag = new AtomicBoolean();
condition = new AtomicBoolean();
}
public void run(){
while (true) {
System.out.println("A");
if (condition.get()) {
flag.set(true);
return ;
}
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
class B implements Runnable {
A a;
B() {
a = new A();
}
public void run() {
while (true) {
System.out.println("B");
if (a.flag.get()) {
System.out.println("Kaboom");
return ;
}
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
B b = new B();
new Thread(b).start();
new Thread(b.a).start();
b.a.condition.set(true);
}
}

Related

How do I run 2 Threads alternately

I am new to Threading and I'm trying to make Output look like: aAbBcCdDeE... .
I searched and tried a lot of stuff but nothing really made it work. In the Exercise you are supposed to do it with a global boolean variable but I didn't really find anything useful and am kinda lost. I appreciate the help!
public class ABCThread implements Runnable {
char c;
public ABCThread(char c) {
this.c = c;
}
#Override
public synchronized void run() {
for (char i = 0; i < 26; i++) {
System.out.println(c++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new ABCThread('a'));
Thread t2 = new Thread(new ABCThread('A'));
t1.start();
t2.start();
}
}
Output:
a
A
B
b
C
c
d
D
e
E
f
F
G
g
H
h
I
i
J
j
Here is the one of the solution to solve the given problem. It uses wait to wait the current thread after printing one letter and notify the other thread to print its letter, and same cycle repeats. The concept of Thread wait and notify is very well explained here.
Short description:
To wait or notify any thread, it (invoking thread) must acquire the lock on any common object. In below example, each thread is acquiring the lock on this (self) (via synchronized run method) to wait and on opponent to notify it (the another thread).
public class App implements Runnable {
char c;
App opponent;
boolean go;
public App(char c, boolean go) {
this.c = c;
this.go = go;
}
public void setOpponent(App opponent) {
this.opponent = opponent;
}
public static void main(String[] args) {
App a = new App('a', true);
App b = new App('A', false);
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
a.setOpponent(b);
b.setOpponent(a);
t1.start();
t2.start();
}
#Override
public synchronized void run() {
for (char i = 0; i < 26; i++) {
try {
if (go) {
System.out.println(c++);
this.wait();
synchronized (opponent) {
opponent.notify();
}
} else {
System.out.println(c++);
synchronized (opponent) {
opponent.notify();
}
this.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Here is the more simplified and understandable version of above code. In this code, both the threads are acquiring lock on same lock object, printing the letter, going in WAIT state (so release the lock) and giving turn to other BLOCKED thread waiting for the lock on lock. The other thread then acquires the lock on lock, prints the letter, notifies the previous thread which was waiting on lock object, and goes into WAIT condition, thus releasing the lock.
public class App2 implements Runnable {
char c;
Object lock;
boolean go;
public App2(char c, boolean go) {
this.c = c;
this.go = go;
}
public void setLock(Object lock) {
this.lock = lock;
}
public static void main(String[] args) {
App2 a = new App2('a', true);
App2 b = new App2('A', false);
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
Object lock = new Object();
a.setLock(lock);
b.setLock(lock);
t1.start();
t2.start();
}
#Override
public void run() {
for (char i = 0; i < 26; i++) {
synchronized (lock) {
try {
if (go) {
System.out.println(c++);
lock.wait();
lock.notify();
} else {
System.out.println(c++);
lock.notify();
lock.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
UPDATE:
Above two approaches will work in most of the cases, but will not guarantee that t1 will be executed before t2 every time. Though t1 is started before t2, but it does not mean that thread scheduler will always pick t1 to execute before t2. To be sure that t1 will execute before t2 in every case, we need to ensure that t2 gets started once t1 is in RUNNABLE state (i.e. running). Below is the one of the way of how we can achieve it:
public class App3 implements Runnable {
char c;
App3 opponent;
boolean go;
boolean createOpponent = false;
public App3(char c, boolean go) {
this.c = c;
this.go = go;
}
public void setOpponent(App3 opponent) {
this.opponent = opponent;
}
public void setCreateOpponent(boolean createOpponent) {
this.createOpponent = createOpponent;
}
public static void main(String[] args) {
App3 a = new App3('a', true);
App3 b = new App3('A', false);
Thread t1 = new Thread(a);
a.setOpponent(b);
a.setCreateOpponent(true);
b.setOpponent(a);
t1.start();
}
#Override
public synchronized void run() {
if (createOpponent) {
setCreateOpponent(false);
new Thread(opponent).start();
}
for (char i = 0; i < 26; i++) {
try {
if (go) {
System.out.println(c++);
this.wait();
synchronized (opponent) {
opponent.notify();
}
} else {
System.out.println(c++);
synchronized (opponent) {
opponent.notify();
}
this.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You're supposed to use a boolean to control which thread prints:
Thread 1 waits for the boolean to be false. Then it prints and sets it true.
Thread 2 waits for the boolean to be true. Then it prints and sets it false.
In this way, the threads will alternate. Also, all of this will be much faster if you use signaling between threads instead of sleep:
import java.util.*;
import java.lang.*;
import java.io.*;
public class ABCThread implements Runnable {
static Object monitor = new Object();
static boolean turn = false;
char c;
final boolean myTurn;
public ABCThread(char c, boolean myTurn) {
this.c = c;
this.myTurn = myTurn;
}
#Override
public void run() {
for (char i = 0; i < 26; i++) {
synchronized(monitor) {
while (turn != myTurn) {
try {
// Note that the lock is release while I'm waiting,
// So the other thread can claim it here.
monitor.wait();
} catch (Exception e) {
}
}
System.out.println(c++);
turn = !myTurn;
monitor.notifyAll();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new ABCThread('a', false));
Thread t2 = new Thread(new ABCThread('A', true));
t1.start();
t2.start();
t1.join();
t2.join();
}
}
What you need? A "shared resource" between threads.
Further: A synchronous FSM (Finite state machine)
Below is code that demonstrated how to achieve that.
public class Main
{
// The shared resource
public static class State {
private int val;
private int nStates;
// Init value and number of states.
public State(int init, int nStates) {
this.val = init;
this.nStates = nStates;
}
int get() {
return val;
}
// Define how to get to next state. For simple use case, just increase then modulo it. eg: 0, 1, 0, 1
// Avoid modulo in-case you need very very high performance.
void next() {
this.val = (this.val + 1) % nStates;
}
}
public static class ABCThread implements Runnable{
private char c;
private State s;
private int type;
public ABCThread(char c, State s, int type) {
this.c = c;
this.s = s;
this.type = type;
}
#Override
public void run() {
try {
for (char i = 0; i < 26; i++) {
// Do things synchronously
synchronized(s){
while(s.get() != type) {
// Wait for our turn.
s.wait();
}
System.out.print(c++);
// Update state
s.next();
// Notify to other threads to do their job.
s.notifyAll();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
// Define the state.
State s = new State(0, 2);
/* Uncomment this block to have 3 synchronous threads. Will print aA1bB2...
s = new State(0, 3);
Thread t3 = new Thread(new ABCThread('1', s, 2));
t3.start();
t3.join();
*/
Thread t1 = new Thread(new ABCThread('a', s, 0));
Thread t2 = new Thread(new ABCThread('A', s, 1));
// Start threads
t1.start();
t2.start();
// Wait for these threads to finish before exit.
t1.join();
t2.join();
}
}
Quick answer:
You can't force a thread to run at a certain moment. What you can do though is let those two run "out of sync" (not related to async coding).
Thread t1 = new Thread(new ABCThread('a'));
Thread.sleep(250);
Thread t2 = new Thread(new ABCThread('A'));
The 1st thread will print about every 500 ms and the 2nd thread will print at 250, 750, 1250, etc.
Note that this would not be a correct way to solve this in real programs. But then again, you would also likely not add Thread.sleep(500) to the run method.
Better:
You need synchronization between the threads. Because you start two threads you can use a boolean.
public class ABCThread implements Runnable {
char c;
static boolean synchronizer = false;
boolean runOn;
public ABCThread(char c, boolean runOn) {
this.c = c;
this.runOn = runOn;
}
#Override
public synchronized void run() {
int count = 0;
while(count < 26)
{
if(runOn != synchronizer)
{
Thread.sleep(100);
continue;
}
count++;
synchronizer = !synchronizer;
System.out.println(c++);
}
}
Thread t1 = new Thread(new ABCThread('a', false));
Thread t2 = new Thread(new ABCThread('A', true));
Just typing this out. It might not compile.
Thread.sleep(100) is just some number. It could possibly be lower, but doesn't matter much for the question.
Even better
The previous code can run with only 2 threads! 1 will just stay stuck with synchronizer = false. If you add a third then the synchronizer won't work because it only has 2 states.
You could add an integer instead of the boolean and another integer amountOfThreads. The amountOfThreads will need to be set to the amount of threads you will start up. Then increase the atomic integer when the thread prints and if the synchronizer (the atomic int) is more than amountOfThreads, set it to 0.
Hope this helps...
public class ABCThread implements Runnable {
char c;
boolean flag;
public ABCThread(char c, boolean flag) {
this.c = c;
this.flag = flag;
}
#Override
public synchronized void run() {
for (char i = 0; i < 52; i++) {
try {
if (flag) {
System.out.println(c++);
notifyAll();
flag = false;
wait(100);
} else {
flag = true;
wait(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new ABCThread('a', true));
Thread t2 = new Thread(new ABCThread('A', false));
t1.start();
t2.start();
}
}
or you can define separate methods for printing small and capital letters and run them in two separate threads
public class ABCThread {
boolean flag;
public ABCThread(boolean flag) {
this.flag = flag;
}
public static void main(String[] args) throws InterruptedException {
ABCThread abc = new ABCThread(false);
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
try {
abc.printSmallLetters();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
abc.printCapitalLetters();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
synchronized void printSmallLetters() throws InterruptedException {
for (char i = 'a'; i < 'z'; i++) {
while (flag == true) {
wait();
}
System.out.println(i);
notifyAll();
flag = true;
}
}
synchronized void printCapitalLetters() throws InterruptedException {
for (char i = 'A'; i < 'Z'; i++) {
while (flag == false) {
wait();
}
System.out.println(i);
notifyAll();
flag = false;
}
}
}
just replace the println by print to get a series output like this
other than that everything seems to be fine,
you can see the output i got in the screenshot above
No way. The order of execution of threads cannot be controlled).You can use Thread.yield(). But yield () - tries to tell the scheduler to execute the next thread, but it stays in the RUNNABLE state.

How to run while loops in different threads? [duplicate]

I got asked this question recently in an interview.
Write a program with two threads (A and B), where A prints 1 , B prints 2 and so on until 50 is reached.
How do we go about doing that ?
The essence of the assignment is to demonstrate how a thread can signal another one. Most common way is to use blocking queues, but here a signal does not carry any information, so a Semaphore is sufficient.
Create thread class which is parameterized with 2 Semaphores: input and output:
class ThreadPrinter implements Runnable {
int counter;
Semaphore ins, outs;
ThreadPrinter(int counter, Semaphore ins, Semaphore outs) {
this.counter = counter;
this.ins = ins;
this.outs = outs;
}
#Override
public void run() {
for (int i = 0; i < 25; i++) {
ins.aquire(); // wait for permission to run
System.out.println("" + counter);
outs.release(); // allow another thread to run
counter += 2;
}
}
Create 2 Semaphores and pass them to 2 threads:
Semaphore a = new Semaphore(1); // first thread is allowed to run immediately
Semaphore b = new Semaphore(0); // second thread has to wait
ThreadPrinter tp1 = new ThreadPrinter(1, a, b);
ThreadPrinter tp2 = new ThreadPrinter(2, b, a);
Note semaphores a and b are passed in different order.
public class Test {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 25; i++) {
synchronized (CommonUtil.mLock) {
incrementCount();
CommonUtil.mLock.notify();
try {
CommonUtil.mLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 25; i++) {
synchronized (CommonUtil.mLock) {
incrementCount();
CommonUtil.mLock.notify();
try {
CommonUtil.mLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
t1.start();
Thread.sleep(400);
t2.start();
t1.join();
t2.join();
}
private static void incrementCount() {
count++;
System.out.println("Count: " + count + " icnremented by: " + Thread.currentThread().getName());
}
}
class CommonUtil {
static final Object mLock = new Object();
}
I encountered the same problem and was expected to use only basics so I choose wait notify on shared object between threads
public class Message implements Runnable {
private static final int N = 10;
private Thread thread;
private static Object object = new Object();
public Message(String name){
thread = new Thread(this, name);
thread.start();
}
public void run(){
for(int i=0; i<N; i++){
synchronized (object) {
System.out.println(i + "--" + thread.getName());
object.notify();
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
In main method :
Message message1 = new Message("Ping");
Message message2 = new Message("Pong");
public class ThreadCounter implements Runnable {
private static int count = 0;
private Thread t;
public ThreadCounter(String tName){
t= new Thread(this, tName);
t.start();
}
#Override
public void run() {
for(int i=1; i<=5; i++){
synchronized (CommonUtil.mLock) {
incrementCount(t.getName());
CommonUtil.mLock.notify();
try {
CommonUtil.mLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void incrementCount(String tName){
System.out.println(tName+": "+(++ThreadCounter.count));
}
public static void main(String[] args) throws InterruptedException {
new ThreadCounter("Thread1");
Thread.sleep(500);
new ThreadCounter("Thread2");
}
}
class CommonUtil{
public static Object mLock = new Object();
}
hi please find answer here...pattern ABABABAB
package com.abhi.ThreadPractice;
public class Test {
public static void main(String[] args) throws InterruptedException {
final Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
// count++;
System.out.println("A");
try {
lock.wait();
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
lock.notify();
//count++;
System.out.println("B");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
This is another solution:
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (lock) {
for (int i = 1; i <= 50; i += 2) {
System.out.println("T1=" + i);
t1turn = false;
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (lock) {
for (int i = 2; i <= 50; i += 2) {
if (t1turn)
try {
lock.wait();
} catch (InterruptedException e) {
}
System.out.println("T2=" + i);
t1turn = true;
lock.notify();
}
}
}
});
t1.start();
t2.start();
May be this is still relevant:
public class MyRunnable implements Runnable {
public static int counter = 0;
public static int turn = 0;
public static Object lock = new Object();
#Override
public void run() {
while (counter < 50) {
synchronized (lock) {
if (turn == 0) {
System.out.println(counter + " from thread "
+ Thread.currentThread().getName());
turn = 1;
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
turn = 0;
lock.notify();
}
}
}
}
}
and then the main function
public static void main(String[] args) {
Thread threadA = new Thread(new MyRunnable());
Thread threadB = new Thread(new MyRunnable ());
threadA.start();
threadB.start();
}
public class PingPong extends Thread {
static StringBuilder object = new StringBuilder("");
public static void main(String[] args) throws InterruptedException {
Thread t1 = new PingPong();
Thread t2 = new PingPong();
t1.setName("\nping");
t2.setName(" pong");
t1.start();
t2.start();
}
#Override
public void run() {
working();
}
void working() {
while (true) {
synchronized (object) {
try {
System.out.print(Thread.currentThread().getName());
object.notify();
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
This was the simplest solution, I was able to think of. It uses a synchronized method and uses the notify() and the wait() to alternatively print the numbers. Hope it helps. :)
public class program implements Runnable
{
static int count =1;
private static final int MAX_COUNT = 50;
public synchronized void print ()
{
System.out.println(Thread.currentThread().getName() + " is printing " + count);
count++;
notify();
try{
if(count>MAX_COUNT)
return;
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
public void run()
{
for(int i=0;i<MAX_COUNT/2;i++)
{
print();
}
}
public static void main(String[] args) {
program x= new program();
Thread t0= new Thread(x);
Thread t1= new Thread(x);
t0.start();
try
{
Thread.sleep(1);
} catch (InterruptedException e){
e.printStackTrace();
}
t1.start();
}
}
//simply use wait and notify and and set a counter and it will do
public class ThreadalternatePrint implements Runnable {
static int counter =0;
#Override
public synchronized void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(counter<51)
{ ++counter;
notify();
System.out.println(Thread.currentThread().getName());
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadalternatePrint obj1 = new ThreadalternatePrint();
Thread Th1 = new Thread(obj1);
Thread Th2 = new Thread(obj1);
Th1.setName("Thread1");
Th2.setName("Thread2");
Th1.start();
Th2.start();
}
}
public class Testing implements Runnable {
private static int counter = 1;
private static final Object lock = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Testing(), "1");
t1.start();
Thread t2 = new Thread(new Testing(), "2");
t2.start();
}
#Override
public void run() {
while (counter<=100) {
synchronized (lock) {
if (counter % 2 == 0) {
System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
counter++;
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (counter % 2 == 1) {
System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
counter++;
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
I have created a pretty basic Solution for it using the Reentrant Lock.
package com.multithreding.trylock;
import java.util.concurrent.locks.ReentrantLock;
public class TryLock extends Thread {
static int intitialCount = 50; //Value till which you want to print
int valueToSubtract = 0; //Value by which difference you want to print the series like 1,2,3
static ReentrantLock alternate = new ReentrantLock();
public TryLock(String name) {
this.setName(name);
}
public void run() {
while (intitialCount > 1) {
if (valueToSubtract > 0) {
alternate.lock();
intitialCount = intitialCount - valueToSubtract;
valueToSubtract = 0;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("value Subtracted " + intitialCount + " by the Thread" + this.getName());
alternate.unlock();
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
valueToSubtract++;
}
}
}
}
package com.multithreding.trylock;
public class AlternatePrint {
public static void main(String[] args) throws InterruptedException{
//You can add as many thread to print then in different number of series
TryLock t1 = new TryLock("Odd One");
TryLock t2 = new TryLock("Even Value");
t1.start();
t2.start();
}
}
This solution is modular as well,
You can add 'n' number of Threads to print the alternate series. i.e Using 3 thread at once
You can also print the series with more than Difference of more than 1. i.e 1,3,5 etc
package thread;
public class Pingpong extends Thread {
static StringBuilder object = new StringBuilder("");
static int i=1;
#Override
public void run() {
working();
}
void working() {
while (i<=10) {
synchronized (object) {
try {
System.out.println(Thread.currentThread().getName() +" "+ i);
i++;
object.notify();
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Pingpong();
Thread t2 = new Pingpong();
t1.setName("Thread1");
t2.setName("Thread2");
t1.start();
t2.start();
}
}
Thread1 1
Thread2 2
Thread1 3
Thread2 4
Thread1 5
Thread2 6
Thread1 7
Thread2 8
Thread1 9
Thread2 10
This answer is generic i.e. not only to print numbers alternately from 2 threads but to execute 2 threads alternately.
The above approaches are commendable but this one doesn't need any lock but instead it uses an AtomicInteger variable alongwith 2 AtomicBooleans to indicate when one thread has finished executing so that the other can finish executing the rest of its remaining execution.
This will work in all 3 cases:
When number of executions of both threads are same.
When first thread finishes before second thread and second thread has more number of executions than first thread.
When second thread finishes before first thread and first thread has more number of executions than second thread.
public class TestAlternateExecutionOfTwoThreads
{
private static final AtomicInteger count = new AtomicInteger(0);
private static final AtomicBoolean firstIsDone = new AtomicBoolean(false);
private static final AtomicBoolean secondIsDone = new AtomicBoolean(false);
// change the below values to change the number of iterations each thread should
// run. In this example, the initial value are hard-coded but you can change
// them as well.
private static final int finalOfFirstThread = 10;
private static final int finalOfSecondThread = 109;
public static void main(String[] args)
{
Runnable r1 = () -> {
int i = 1;
for(; i <= finalOfFirstThread; )
{
while(count.get() == 0)
{
System.out.println(i);
count.incrementAndGet();
i++;
}
if(count.get() == 1 && secondIsDone.get() && i != (finalOfFirstThread + 1))
{
System.out.println(i);
i++;
}
}
firstIsDone.set(true);
};
Runnable r2 = () -> {
int j = 100;
for (; j <= finalOfSecondThread; )
{
while(count.get() == 1)
{
System.out.println(j);
count.decrementAndGet();
j++;
}
if(count.get() == 0 && firstIsDone.get() && j != (finalOfSecondThread + 1))
{
System.out.println(j);
j++;
}
}
secondIsDone.set(true);
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
I guess this might help.
Although it is not standard but i hope it provides a simpler approach.
public class ThreadDemo
{
public static void main (String [] args)
{
PrintDemo pd=new PrintDemo();
MyThread1 mt1 = new MyThread1 ("T1",pd);
MyThread2 mt2 = new MyThread2 ("T2",pd);
mt1.start ();
mt2.start();
}
}
class PrintDemo {
private boolean oddFlag=true;
public synchronized void printOdd(int i,String tName){
if(oddFlag==false){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("\nThread "+tName+" count:"+i);
oddFlag=false;
notify();
}
}
public synchronized void printEven(int i,String tName){
if(oddFlag==true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("\nThread "+tName+" count:"+i);
oddFlag=true;
notify();
}
}
}
class MyThread1 extends Thread
{
private PrintDemo pd;
private String name;
MyThread1(String threadName,PrintDemo pd){
this.name=threadName;
this.pd=pd;
}
public void run ()
{
for(int i=1;i<=50;i+=2){
pd.printOdd(i,name);
}
}
}
class MyThread2 extends Thread
{
private PrintDemo pd;
private String name;
MyThread2(String threadName,PrintDemo pd){
this.name=threadName;
this.pd=pd;
}
public void run ()
{
for(int i=2;i<=50;i+=2){
pd.printEven(i,name);
}
}
}

How to execute four threads consecutively one by one in java? [duplicate]

I have 3 threads
1st printing A
2nd printing B
3rd printing C
I want to print in sequence A B C A B C A B C and so on.....
So I wrote the program below, but I am not able to achieve the same.
I am aware of the problem that when status=1 at that time say for example B1 and C1 thread are waiting and when I do notifyAll() both waiting thread wake up and depending on CPU allocation it might print B or C.
in this case I want only B to be printed after A.
what modification I need to do.
public class NotifyAllExample {
int status=1;
public static void main(String[] args) {
NotifyAllExample notifyAllExample = new NotifyAllExample();
A1 a=new A1(notifyAllExample);
B1 b=new B1(notifyAllExample);
C1 c=new C1(notifyAllExample);
a.start();
b.start();
c.start();
}
}
class A1 extends Thread{
NotifyAllExample notifyAllExample;
A1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
#Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=1){
notifyAllExample.wait();
}
System.out.print("A ");
notifyAllExample.status = 2;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 1 :"+e.getMessage());
}
}
}
class B1 extends Thread{
NotifyAllExample notifyAllExample;
B1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
#Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=2){
notifyAllExample.wait();
}
System.out.print("B ");
notifyAllExample.status = 3;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 2 :"+e.getMessage());
}
}
}
class C1 extends Thread{
NotifyAllExample notifyAllExample;
C1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
#Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=3){
notifyAllExample.wait();
}
System.out.print("C ");
notifyAllExample.status = 1;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 3 :"+e.getMessage());
}
}
}
Convert those IF statements to WHILE statements to get the desired behavior:
if (notifyAllExample.status != 2){
notifyAllExample.wait();
}
to
while (notifyAllExample.status != 2){
notifyAllExample.wait();
}
This will ensure that if a thread is notified, it won't go out of the while loop until the status value is what it expects.
Also, mark status as volatile so that the threads won't have a local copy.
public class RunThreadsInOrder implements Runnable {
static int numThread = 1;
static int threadAllowedToRun = 1;
int myThreadID;
private static Object myLock = new Object();
public RunThreadsInOrder() {
this.myThreadID = numThread++;
System.out.println("Thread ID:" + myThreadID);
}
#Override
public void run() {
synchronized (myLock) {
while (myThreadID != threadAllowedToRun) {
try {
myLock.wait();
} catch (InterruptedException e) {
} catch (Exception e) {}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("myThreadID is running: " + myThreadID);
myLock.notifyAll();
threadAllowedToRun++;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(new RunThreadsInOrder());
Thread t2 = new Thread(new RunThreadsInOrder());
Thread t3 = new Thread(new RunThreadsInOrder());
Thread t4 = new Thread(new RunThreadsInOrder());
Thread t5 = new Thread(new RunThreadsInOrder());
Thread t6 = new Thread(new RunThreadsInOrder());
Thread t7 = new Thread(new RunThreadsInOrder());
t7.start();
t6.start();
t5.start();
t4.start();
t3.start();
t2.start();
t1.start();
}
}
public class Main {
public static void main(String[] args) throws IOException{
Thread t1 = new Thread(new A(), "1");
Thread t2 = new Thread(new A(), "2");
Thread t3 = new Thread(new A(), "3");
t1.start();
try{
t1.join();
}catch (Exception e){
}
t2.start();
try{
t2.join();
}catch (Exception e){
}
t3.start();
try{
t3.join();
}catch (Exception e){
}
}
}
class A implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
or you can use Executor Framework
public class Sequence {
int valve = 1;
public static void main(String[] args){
Sequence s = new Sequence();
ExecutorService es = Executors.newFixedThreadPool(3);
List<Runnable> rList = new ArrayList<>();
rList.add(new A(s));
rList.add(new B(s));
rList.add(new C(s));
for(int i = 0; i < rList.size(); i++){
es.submit(rList.get(i));
}
es.shutdown();
}
}
class A implements Runnable{
Sequence s;
A(Sequence s){
this.s = s;
}
public void run(){
synchronized (s) {
for (int i = 0; i < 10; i++) {
while (s.valve != 1) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
s.valve = 2;
s.notifyAll();
}
}
}
}
class B implements Runnable{
Sequence s;
B(Sequence s){
this.s = s;
}
public void run() {
synchronized (s) {
for (int i = 0; i < 10; i++) {
while (s.valve != 2) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
s.valve = 3;
s.notifyAll();
}
}
}
}
class C implements Runnable{
Sequence s;
C(Sequence s){
this.s = s;
}
public void run() {
synchronized (s) {
for(int i = 0; i < 10; i++) {
while (s.valve != 3) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
s.valve = 1;
s.notifyAll();
}
}
}
}
In the first case the join for each thread causes the threads to wait for one another. In the second case a list stores the threads and executor executes them one after another creating 3 threads
Another way to do this is where only one runnable class is present and communication between thread is done via static variable in the main class and a variable in the runnable class
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Seq {
int i = 1;
public static void main(String[] args){
Seq s = new Seq();
Common c1 = new Common(s, 1);
Common c2 = new Common(s, 2);
Common c3 = new Common(s, 3);
List<Runnable> l = new ArrayList<>();
l.add(c1);
l.add(c2);
l.add(c3);
ExecutorService es = Executors.newFixedThreadPool(3);
for(int i = 0; i < 3; i++){
es.submit(l.get(i));
}
es.shutdown();
}
}
class Common implements Runnable{
Seq s;
int o;
Common(Seq s, int o){
this.s = s;
this.o = o;
}
public void run(){
synchronized (s) {
for (int z = 0; z < 100; z++) {
if(s.i > 3)
s.i = 1;
while (s.i != o) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(o);
s.i++;
s.notifyAll();
}
}
}
}
I was asked to write a similar program in an interview with the added condition that it should be extensible in a way that we can provide our own count of threads and they should print characters with the first thread printing 'A' and then the subsequent threads printing B, C, D and so on. Here's how I did it.
public class AlternateCharPrinter {
public static char ch = 65;
private static void createAndStartThreads(int count) {
Object lock = new Object();
for (int i = 0; i < count; i++) {
new Thread(new AlternateCharRunner((char) (65 + i), lock)).start();
}
}
public static void main(String[] args) {
createAndStartThreads(4);
}
}
class AlternateCharRunner implements Runnable {
private char ch;
private Object lock;
private static int runnerCount;
public AlternateCharRunner(char ch, Object lock) {
this.ch = ch;
this.lock = lock;
runnerCount++;
}
#Override
public void run() {
while (true) {
synchronized (lock) {
while (ch != AlternateCharPrinter.ch) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(AlternateCharPrinter.ch++);
if (AlternateCharPrinter.ch == (65 + runnerCount)) {
AlternateCharPrinter.ch = 65;
}
lock.notifyAll();
}
}
}
}
You need to replace
if (notifyAllExample.status!=1)
with
while (notifyAllExample.status!=1)
and same thing in the other 2 classes. If not, then as soon as the wait exits the thread continues without knowing if it is its turn.
Replace:
if(notifyAllExample.status!=1){
notifyAllExample.wait();
}
with:
while(notifyAllExample.status!=1){
notifyAllExample.wait();
}
in all classes accordingly.
The simplest solution to solve this can be following way:
public class PrintInOrder implements Runnable {
private int valueToPrint;
private int id;
private static int turn = 1;
private static int RESET_TURN_THRESHOLD = 3;
public PrintInOrder() {
this.valueToPrint = -1;
}
public PrintInOrder(int id, int val) {
this.id = id;
this.valueToPrint = val;
}
#Override
public void run() {
while(true) {
if (turn == this.id) {
System.out.println(Thread.currentThread().getName() + "::::" + valueToPrint);
turn++;
}
if (turn > RESET_TURN_THRESHOLD) {
turn = 1;
}
}
}
public static void main(String []args) {
Thread t1 = new Thread(new PrintInOrder(1, 1));
t1.setName("THREAD-1");
t1.start();
Thread t2 = new Thread(new PrintInOrder(2, 2));
t2.setName("THREAD-2");
t2.start();
Thread t3 = new Thread(new PrintInOrder(3, 3));
t3.setName("THREAD-3");
t3.start();
}
}
/*
OUTPUT::::
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
...
*/
Here is my solution -
I have created three threads each thread knows what it needs to print and what comes after it.
I have also created a Class NLock which holds the next word which needs to be printed.
Whenever a thread is able to acquire NLock lock then it checks
if it's his turn if yes then it prints the word and set the next value to be printed in NLock or else it waits till it's his turn
public class SynchronizeThreeThreads {
public static void main(String args[]) throws InterruptedException {
NLock lock=new NLock("A");
Thread a =new Thread(new PrintInOrder("A","B",lock));
Thread b =new Thread(new PrintInOrder("B","C",lock));
Thread c =new Thread(new PrintInOrder("C","A",lock));
a.start();
b.start();
c.start();
c.join(); // Once all is done main thread will exit
System.out.println("Done");
}
}
class NLock{
private String value;
public NLock(String value) {
this.value=value;
}
public String getValue() {
return value;
}
public void setValue(String next) {
this.value=next;
}
}
class PrintInOrder implements Runnable{
private String word;
private String next;
private NLock lock;
public PrintInOrder(String word, String next,NLock lock){
this.word=word;
this.next=next;
this.lock=lock;
}
#Override
public void run() {
int i=0;
while(i<3) {
synchronized (lock) {
try {
//Check if it's my turn
if(lock.getValue().equals(word)) {
System.out.println(this.word);
//Set what next needs to be printed
//So that when that thread wakes up it knows that it's his turn
lock.setValue(next);
i++;
lock.notifyAll();
Thread.sleep(100);
}
else //Nope not my turn wait
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Below is the output
A
B
C
A
B
C
A
B
C
Done
This is my attempt to solve the same. Any suggestions are welcome. This is the complete running code.
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
#Slf4j
public class SeqExecution {
static class SeqThread extends Thread {
private static final Object lock = new Object();
private static final AtomicInteger AUTO_COUNTER = new AtomicInteger();
private static final TrackExecution trackExecution = new TrackExecution();
private final int seqNo;
SeqThread(Runnable runnable) {
super(runnable);
this.seqNo = AUTO_COUNTER.getAndIncrement();
}
#SneakyThrows
#Override
public void run() {
while (true) {
synchronized (lock) {
while (trackExecution.CUR_EXECUTION.get() != this.seqNo) {
try {
lock.wait(100);
} catch (Exception e) {}
}
//log.info("Thread: {} is running", this.seqNo);
super.run();
sleep(1000);
trackExecution.increment();
lock.notifyAll();
}
}
}
static class TrackExecution {
private final AtomicInteger CUR_EXECUTION = new AtomicInteger();
int get() {
return CUR_EXECUTION.get();
}
synchronized void increment() {
var val = CUR_EXECUTION.incrementAndGet();
if (val >= SeqThread.AUTO_COUNTER.get()) {
CUR_EXECUTION.set(0);
}
}
}
}
public static void main(String[] args) {
final var seqThreads = List.of(new SeqThread(() -> System.out.print("A ")),
new SeqThread(() -> System.out.print("B ")),
new SeqThread(() -> System.out.print("C ")));
seqThreads.forEach(Thread::start);
seqThreads.forEach(t -> {
try {
t.join();
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
});
}
}
I think it's simpler to achieve this using join.
Example:
public static void main(String[] args) {
final Thread t1 = new Thread("t1") {
#Override
public void run() {
System.out.println("i am thread: " + Thread.currentThread().getName());
}
};
final Thread t2 = new Thread(t1, "t2") {
#Override
public void run() {
t1.start();
try {
t1.join();
} catch ( InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("i am thread: " + Thread.currentThread().getName());
}
};
Thread t3 = new Thread(t2, "t3") {
#Override
public void run() {
t2.start();
try {
t2.join();
} catch ( InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("i am thread: " + Thread.currentThread().getName());
}
};
t3.start();
}
Here is my solution please try and let me know
package thread;
class SyncPrinter {
public static void main(String[] args) {
SyncPrinterAction printAction1 = new SyncPrinterAction(new int[]{1,5,9,13}, true);
SyncPrinterAction printAction2 = new SyncPrinterAction(new int[]{2,6,10,14}, true);
SyncPrinterAction printAction3 = new SyncPrinterAction(new int[]{3,7,11,15}, true);
SyncPrinterAction printAction4 = new SyncPrinterAction(new int[]{4,8,12,16}, false);
printAction1.setDependentAction(printAction4);
printAction2.setDependentAction(printAction1);
printAction3.setDependentAction(printAction2);
printAction4.setDependentAction(printAction3);
new Thread(printAction1, "T1").start();;
new Thread(printAction2, "T2").start();
new Thread(printAction3, "T3").start();
new Thread(printAction4, "T4").start();
}
}
class SyncPrinterAction implements Runnable {
private volatile boolean dependent;
private SyncPrinterAction dependentAction;
int[] data;
public void setDependentAction(SyncPrinterAction dependentAction){
this.dependentAction = dependentAction;
}
public SyncPrinterAction( int[] data, boolean dependent) {
this.data = data;
this.dependent = dependent;
}
public SyncPrinterAction( int[] data, SyncPrinterAction dependentAction, boolean dependent) {
this.dependentAction = dependentAction;
this.data = data;
this.dependent = dependent;
}
#Override
public void run() {
synchronized (this) {
for (int value : data) {
try {
while(dependentAction.isDependent())
//System.out.println("\t\t"+Thread.currentThread().getName() + " :: Waithing for dependent action to complete");
wait(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
dependentAction.setDependent(true);
System.out.println(Thread.currentThread().getName() + " :: " +value);
dependent = false;
}
}
}
private void setDependent(boolean dependent) {
this.dependent = dependent;
}
private boolean isDependent() {
return dependent;
}
}

Odd even sequence java 2 thread

I am trying to write a program with two Java threads. One shall print odd and the other shall print even numbers. The output should be in sequence. My code is not working properly. Please correct it and tell me what was the error.
public class App {
public static void main(String[] args) {
ThrdO to=new ThrdO();
Thread t1=new Thread(to);
ThredE te=new ThredE();
Thread t2=new Thread(te);
t1.start();
t2.start();
}
}
public class ThrdO implements Runnable{
PrintCl pcl =new PrintCl();
#Override
public void run() {
for(int i=0;i<10;i+=2)
pcl.Even(i);
}
}
public class ThredE implements Runnable {
PrintCl pcl =new PrintCl();
#Override
public void run() {
for(int i=1;i<10;i+=2)
try {
pcl.odd(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class PrintCl {
public void Even(int n) {
synchronized (this) {
System.out.println(n);
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void odd(int n) throws InterruptedException {
synchronized (this) {
System.out.println(n);
this.notifyAll();
this.wait();
}
}
}
getting output
0 ,1
This is a much cleaner way of achieving what you want, without ugly sleeps in the code, not to mention that it will run faster than code with a sleep in it, for obvious reasons.
public class App {
public static void main(String[] args) {
PrintCl pcl = new PrintCl();
Thread t1 = new Thread(new ThrdEven(pcl));
Thread t2 = new Thread(new ThrdOdd(pcl));
t1.start();
t2.start();
}
}
public class ThrdEven implements Runnable {
private PrintCl pcl = null;
public ThrdEven(PrintCl pcl) {
this.pcl = pcl;
}
#Override
public void run() {
for (int i = 0; i < 10; i += 2) {
pcl.Even(i);
}
}
}
public class ThrdOdd implements Runnable {
private PrintCl pcl = null;
public ThrdOdd(PrintCl pcl) {
this.pcl = pcl;
}
#Override
public void run() {
for (int i = 1; i < 10; i += 2) {
pcl.odd(i);
}
}
}
public class PrintCl {
private final Object _lock = new Object();
private boolean isEvenAllowed = true;
public void Even(int n) {
synchronized (this._lock) {
while (!this.isEvenAllowed) {
try {
this._lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
System.out.println(n);
this.isEvenAllowed = false;
this._lock.notifyAll();
}
}
public void odd(int n) {
synchronized (this._lock) {
while (this.isEvenAllowed) {
try {
this._lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
System.out.println(n);
this.isEvenAllowed = true;
this._lock.notifyAll();
}
}
}
Please try following changes in your code:
public class App {
public static void main(String[] args) throws InterruptedException {
PrintCl pcl =new PrintCl();
ThrdO to=new ThrdO();
to.setPcl(pcl);
Thread t1=new Thread(to);
ThredE te=new ThredE();
te.setPcl(pcl);
Thread t2=new Thread(te);
t1.start();
Thread.sleep(1000);
t2.start();
}
}
And for Thrd0:
public class ThrdO implements Runnable {
PrintCl pcl =null;
#Override
public void run() {
for(int i=0;i<10;i+=2)
pcl.Even(i);
}
public PrintCl getPcl() {
return pcl;
}
public void setPcl(PrintCl pcl) {
this.pcl = pcl;
}
}
ThredE:
public class ThredE implements Runnable {
PrintCl pcl =null;
#Override
public void run() {
for(int i=1;i<10;i+=2)
try {
pcl.odd(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public PrintCl getPcl() {
return pcl;
}
public void setPcl(PrintCl pcl) {
this.pcl = pcl;
}
}
Your code has two basic problems
Every thread have its own printing resource . Hence once printing their first number they are waiting for notification endlessly.
Once you will fix this issue , Another issue is your one thread will be finished but second thread would still be waiting for its notification and it will never die.
I have fixed both issues in below code
public class Test {
public static void main(String[] args) throws InterruptedException {
PrintCl pcl =new PrintCl();
ThrdO to=new ThrdO(pcl);
Thread t1=new Thread(to);
ThredE te=new ThredE(pcl);
Thread t2=new Thread(te);
t1.start();
Thread.sleep(1000);// just to ensure that T1 should start first
t2.start();
}
}
class ThrdO implements Runnable{
private PrintCl pcl;
public ThrdO(PrintCl pcl) {
this.pcl = pcl;
}
#Override
public void run() {
for(int i=0;i<10;i+=2) {
try {
pcl.Even(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (pcl){
System.out.println("Releasing lock on pcl");
pcl.notify();
}
System.out.println("ThrdO has finished its working");
}
}
class ThredE implements Runnable {
PrintCl pcl ;
public ThredE(PrintCl pcl) {
this.pcl = pcl;
}
#Override
public void run() {
for (int i = 1; i < 10; i += 2) {
try {
pcl.odd(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (pcl){
System.out.println("Releasing lock on pcl ");
pcl.notify();
}
System.out.println("ThredE has finished its working");
}
}
class PrintCl {
public void Even(int n) throws InterruptedException {
synchronized (this) {
System.out.println("even - "+n);
this.notifyAll();
this.wait();
}
}
public void odd(int n) throws InterruptedException {
synchronized (this) {
System.out.println("odd "+n);
this.notifyAll();
this.wait();
}
}
}

Writing a program with 2 threads which prints alternatively

I got asked this question recently in an interview.
Write a program with two threads (A and B), where A prints 1 , B prints 2 and so on until 50 is reached.
How do we go about doing that ?
The essence of the assignment is to demonstrate how a thread can signal another one. Most common way is to use blocking queues, but here a signal does not carry any information, so a Semaphore is sufficient.
Create thread class which is parameterized with 2 Semaphores: input and output:
class ThreadPrinter implements Runnable {
int counter;
Semaphore ins, outs;
ThreadPrinter(int counter, Semaphore ins, Semaphore outs) {
this.counter = counter;
this.ins = ins;
this.outs = outs;
}
#Override
public void run() {
for (int i = 0; i < 25; i++) {
ins.aquire(); // wait for permission to run
System.out.println("" + counter);
outs.release(); // allow another thread to run
counter += 2;
}
}
Create 2 Semaphores and pass them to 2 threads:
Semaphore a = new Semaphore(1); // first thread is allowed to run immediately
Semaphore b = new Semaphore(0); // second thread has to wait
ThreadPrinter tp1 = new ThreadPrinter(1, a, b);
ThreadPrinter tp2 = new ThreadPrinter(2, b, a);
Note semaphores a and b are passed in different order.
public class Test {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 25; i++) {
synchronized (CommonUtil.mLock) {
incrementCount();
CommonUtil.mLock.notify();
try {
CommonUtil.mLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 25; i++) {
synchronized (CommonUtil.mLock) {
incrementCount();
CommonUtil.mLock.notify();
try {
CommonUtil.mLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
t1.start();
Thread.sleep(400);
t2.start();
t1.join();
t2.join();
}
private static void incrementCount() {
count++;
System.out.println("Count: " + count + " icnremented by: " + Thread.currentThread().getName());
}
}
class CommonUtil {
static final Object mLock = new Object();
}
I encountered the same problem and was expected to use only basics so I choose wait notify on shared object between threads
public class Message implements Runnable {
private static final int N = 10;
private Thread thread;
private static Object object = new Object();
public Message(String name){
thread = new Thread(this, name);
thread.start();
}
public void run(){
for(int i=0; i<N; i++){
synchronized (object) {
System.out.println(i + "--" + thread.getName());
object.notify();
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
In main method :
Message message1 = new Message("Ping");
Message message2 = new Message("Pong");
public class ThreadCounter implements Runnable {
private static int count = 0;
private Thread t;
public ThreadCounter(String tName){
t= new Thread(this, tName);
t.start();
}
#Override
public void run() {
for(int i=1; i<=5; i++){
synchronized (CommonUtil.mLock) {
incrementCount(t.getName());
CommonUtil.mLock.notify();
try {
CommonUtil.mLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void incrementCount(String tName){
System.out.println(tName+": "+(++ThreadCounter.count));
}
public static void main(String[] args) throws InterruptedException {
new ThreadCounter("Thread1");
Thread.sleep(500);
new ThreadCounter("Thread2");
}
}
class CommonUtil{
public static Object mLock = new Object();
}
hi please find answer here...pattern ABABABAB
package com.abhi.ThreadPractice;
public class Test {
public static void main(String[] args) throws InterruptedException {
final Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
// count++;
System.out.println("A");
try {
lock.wait();
lock.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
lock.notify();
//count++;
System.out.println("B");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
This is another solution:
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (lock) {
for (int i = 1; i <= 50; i += 2) {
System.out.println("T1=" + i);
t1turn = false;
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (lock) {
for (int i = 2; i <= 50; i += 2) {
if (t1turn)
try {
lock.wait();
} catch (InterruptedException e) {
}
System.out.println("T2=" + i);
t1turn = true;
lock.notify();
}
}
}
});
t1.start();
t2.start();
May be this is still relevant:
public class MyRunnable implements Runnable {
public static int counter = 0;
public static int turn = 0;
public static Object lock = new Object();
#Override
public void run() {
while (counter < 50) {
synchronized (lock) {
if (turn == 0) {
System.out.println(counter + " from thread "
+ Thread.currentThread().getName());
turn = 1;
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
turn = 0;
lock.notify();
}
}
}
}
}
and then the main function
public static void main(String[] args) {
Thread threadA = new Thread(new MyRunnable());
Thread threadB = new Thread(new MyRunnable ());
threadA.start();
threadB.start();
}
public class PingPong extends Thread {
static StringBuilder object = new StringBuilder("");
public static void main(String[] args) throws InterruptedException {
Thread t1 = new PingPong();
Thread t2 = new PingPong();
t1.setName("\nping");
t2.setName(" pong");
t1.start();
t2.start();
}
#Override
public void run() {
working();
}
void working() {
while (true) {
synchronized (object) {
try {
System.out.print(Thread.currentThread().getName());
object.notify();
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
This was the simplest solution, I was able to think of. It uses a synchronized method and uses the notify() and the wait() to alternatively print the numbers. Hope it helps. :)
public class program implements Runnable
{
static int count =1;
private static final int MAX_COUNT = 50;
public synchronized void print ()
{
System.out.println(Thread.currentThread().getName() + " is printing " + count);
count++;
notify();
try{
if(count>MAX_COUNT)
return;
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
public void run()
{
for(int i=0;i<MAX_COUNT/2;i++)
{
print();
}
}
public static void main(String[] args) {
program x= new program();
Thread t0= new Thread(x);
Thread t1= new Thread(x);
t0.start();
try
{
Thread.sleep(1);
} catch (InterruptedException e){
e.printStackTrace();
}
t1.start();
}
}
//simply use wait and notify and and set a counter and it will do
public class ThreadalternatePrint implements Runnable {
static int counter =0;
#Override
public synchronized void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(counter<51)
{ ++counter;
notify();
System.out.println(Thread.currentThread().getName());
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadalternatePrint obj1 = new ThreadalternatePrint();
Thread Th1 = new Thread(obj1);
Thread Th2 = new Thread(obj1);
Th1.setName("Thread1");
Th2.setName("Thread2");
Th1.start();
Th2.start();
}
}
public class Testing implements Runnable {
private static int counter = 1;
private static final Object lock = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Testing(), "1");
t1.start();
Thread t2 = new Thread(new Testing(), "2");
t2.start();
}
#Override
public void run() {
while (counter<=100) {
synchronized (lock) {
if (counter % 2 == 0) {
System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
counter++;
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (counter % 2 == 1) {
System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
counter++;
try {
lock.notifyAll();
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
I have created a pretty basic Solution for it using the Reentrant Lock.
package com.multithreding.trylock;
import java.util.concurrent.locks.ReentrantLock;
public class TryLock extends Thread {
static int intitialCount = 50; //Value till which you want to print
int valueToSubtract = 0; //Value by which difference you want to print the series like 1,2,3
static ReentrantLock alternate = new ReentrantLock();
public TryLock(String name) {
this.setName(name);
}
public void run() {
while (intitialCount > 1) {
if (valueToSubtract > 0) {
alternate.lock();
intitialCount = intitialCount - valueToSubtract;
valueToSubtract = 0;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("value Subtracted " + intitialCount + " by the Thread" + this.getName());
alternate.unlock();
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
valueToSubtract++;
}
}
}
}
package com.multithreding.trylock;
public class AlternatePrint {
public static void main(String[] args) throws InterruptedException{
//You can add as many thread to print then in different number of series
TryLock t1 = new TryLock("Odd One");
TryLock t2 = new TryLock("Even Value");
t1.start();
t2.start();
}
}
This solution is modular as well,
You can add 'n' number of Threads to print the alternate series. i.e Using 3 thread at once
You can also print the series with more than Difference of more than 1. i.e 1,3,5 etc
package thread;
public class Pingpong extends Thread {
static StringBuilder object = new StringBuilder("");
static int i=1;
#Override
public void run() {
working();
}
void working() {
while (i<=10) {
synchronized (object) {
try {
System.out.println(Thread.currentThread().getName() +" "+ i);
i++;
object.notify();
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Pingpong();
Thread t2 = new Pingpong();
t1.setName("Thread1");
t2.setName("Thread2");
t1.start();
t2.start();
}
}
Thread1 1
Thread2 2
Thread1 3
Thread2 4
Thread1 5
Thread2 6
Thread1 7
Thread2 8
Thread1 9
Thread2 10
This answer is generic i.e. not only to print numbers alternately from 2 threads but to execute 2 threads alternately.
The above approaches are commendable but this one doesn't need any lock but instead it uses an AtomicInteger variable alongwith 2 AtomicBooleans to indicate when one thread has finished executing so that the other can finish executing the rest of its remaining execution.
This will work in all 3 cases:
When number of executions of both threads are same.
When first thread finishes before second thread and second thread has more number of executions than first thread.
When second thread finishes before first thread and first thread has more number of executions than second thread.
public class TestAlternateExecutionOfTwoThreads
{
private static final AtomicInteger count = new AtomicInteger(0);
private static final AtomicBoolean firstIsDone = new AtomicBoolean(false);
private static final AtomicBoolean secondIsDone = new AtomicBoolean(false);
// change the below values to change the number of iterations each thread should
// run. In this example, the initial value are hard-coded but you can change
// them as well.
private static final int finalOfFirstThread = 10;
private static final int finalOfSecondThread = 109;
public static void main(String[] args)
{
Runnable r1 = () -> {
int i = 1;
for(; i <= finalOfFirstThread; )
{
while(count.get() == 0)
{
System.out.println(i);
count.incrementAndGet();
i++;
}
if(count.get() == 1 && secondIsDone.get() && i != (finalOfFirstThread + 1))
{
System.out.println(i);
i++;
}
}
firstIsDone.set(true);
};
Runnable r2 = () -> {
int j = 100;
for (; j <= finalOfSecondThread; )
{
while(count.get() == 1)
{
System.out.println(j);
count.decrementAndGet();
j++;
}
if(count.get() == 0 && firstIsDone.get() && j != (finalOfSecondThread + 1))
{
System.out.println(j);
j++;
}
}
secondIsDone.set(true);
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
I guess this might help.
Although it is not standard but i hope it provides a simpler approach.
public class ThreadDemo
{
public static void main (String [] args)
{
PrintDemo pd=new PrintDemo();
MyThread1 mt1 = new MyThread1 ("T1",pd);
MyThread2 mt2 = new MyThread2 ("T2",pd);
mt1.start ();
mt2.start();
}
}
class PrintDemo {
private boolean oddFlag=true;
public synchronized void printOdd(int i,String tName){
if(oddFlag==false){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("\nThread "+tName+" count:"+i);
oddFlag=false;
notify();
}
}
public synchronized void printEven(int i,String tName){
if(oddFlag==true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("\nThread "+tName+" count:"+i);
oddFlag=true;
notify();
}
}
}
class MyThread1 extends Thread
{
private PrintDemo pd;
private String name;
MyThread1(String threadName,PrintDemo pd){
this.name=threadName;
this.pd=pd;
}
public void run ()
{
for(int i=1;i<=50;i+=2){
pd.printOdd(i,name);
}
}
}
class MyThread2 extends Thread
{
private PrintDemo pd;
private String name;
MyThread2(String threadName,PrintDemo pd){
this.name=threadName;
this.pd=pd;
}
public void run ()
{
for(int i=2;i<=50;i+=2){
pd.printEven(i,name);
}
}
}

Categories