Threads Waiting in Line Queue, Java - java

I'm In a sticky situation. I know this is almost as far as i can get for now, but what i want to do is actually to make an array of thread (or many thread) and accommodate number of threads in queue in the line, so for example i can accommodate 3 thread at a time, i make the first 3 thread run, then make the other wait, when there is free like for example the 1 is free or terminated the other one can start running.
also i want to make sure if the thread can run or not if the thread that is running is the same as the other thread's gender.
Thread myThreads[] = new Thread[LN.GetLine().length()];
int l=LN.GetLine().length();
for (int j = 0; j < LN.GetLine().length(); j++) {
String Name = CR.Gender(LN.GetLine().charAt(j)) + j;
myThreads[j] = new Thread(new MyThread(Name,LN));
myThreads[j].setPriority(l);
System.out.println(myThreads[j].toString());
l--;
}
for(int b=0;b<LN.GetLine().length();b++){
myThreads[b].start();
synchronized(myThreads[b]){
try{
myThreads[b].wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
For now what i can make is accommodate or make 1 thread run at a time.
(Yes this is a Machine bathroom Problem)
My real question is. if i Edit the function run() in myThread() that has a wait() or just plain put a System.out.println(getName() + " is Using");
And how will the thread know in their run() function that other thread is running.
public class MyThread extends Thread {
public MyThread(String id) {
super(id);
}
public void run(){
System.out.println(getName() + " is Using");
>>>Put wait if other thread running<<<<
>>>If can use or not if same gender<<<<
}
Or should i just implement that outside? or put the Waiting outside?
Also i'm really new in Threading so i haven't really explored with Sleep and Interrupt yet.

You can do this without wait.
Here is an example:
public class MyThread extends Thread {
static final Object gender1Lock = new Object();
static final Object gender2Lock = new Object();
int gender;
public MyThread(String id, int gender) {
super(id);
this.gender = gender;
}
public void run(){
System.out.println(getName() + " is waiting");
if(gender == 1){
synchronized(gender1Lock){ // ocupy gender 1
System.out.println(getName() + " is Using");
}
}else if(gender == 2){
synchronized(gender1Lock){ // ocupy gender 2
System.out.println(getName() + " is Using");
}
}
}
}
Since only one thread can synchronize on an object at a time it means that only one thread of a given gender can run at a time. This creates sequential execution of all threads of a given gender.
And here is an example of using this kind of thread.
for(int i = 0; i < 20; i++){
new MyThread("Person " + i, (i%2 == 0) ? 1 : 2).start();
}

... so for example i can accommodate 3 thread at a time, i make the first 3 thread run, then make the other wait, when there is free like for example the 1 is free or terminated the other one can start running.
This can be achieved using a Executor with a fixed Thread Pool.
ExecutorService m = Executors.newFixedThreadPool(3)
ExecutorService f = Executors.newFixedThreadPool(3)
for(;;) {
Object o = new Object();
m.execute(() -> {...; o.wait(); /* You know notify was called on o at this point hence f run clause is running or has just run */ ...})
f.execute(() -> {...; o.notify(); ...})
}
Since this a a batroom the ques are seperate an there will be fixed number of toilets:
ExecutorService m = Executors.newFixedThreadPool(3)
ExecutorService f = Executors.newFixedThreadPool(3)
for(;;) {
Person male = getNextMale();
m.execute(() -> {...; /* do something with male */ ...})
Person female = getNextFemale();
f.execute(() -> {...; /* do something with female */ ...})
}
To implement the queue you can use one of the BlockingQueue implementations.

I would just use two single thread executors obtained via Executors.newSingleThreadExecutor();, one for each gender, and then submit the task to the appropriate executor. Simple and done.
And if you only have one bathroom, then only one executor is needed. For example:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class GetInLine {
public static void main(String[] args) {
List<MyRunnable> myRunnables = new ArrayList<>();
myRunnables.add(new MyRunnable("Bob", false));
myRunnables.add(new MyRunnable("Jill", true));
myRunnables.add(new MyRunnable("Frank", false));
myRunnables.add(new MyRunnable("Amy", true));
myRunnables.add(new MyRunnable("Pete", false));
myRunnables.add(new MyRunnable("Diane", true));
ExecutorService myExecutor = Executors.newSingleThreadExecutor();
for (MyRunnable myRunnable : myRunnables) {
myExecutor.submit(myRunnable);
}
myExecutor.shutdown();
}
}
public class MyRunnable implements Runnable {
private static final int MIN_SLEEP_TIME = 500;
private static final int MAX_SLEEP_TIME = 2000;
private static final int FEMALE_SLEEP_BONUS = 500;
private Random random = new Random();
private String name;
private boolean female;
public MyRunnable(String name, boolean female) {
this.name = name;
this.female = female;
}
public String getName() {
return name;
}
public boolean isFemale() {
return female;
}
#Override
public void run() {
System.out.println(name + " is using");
try {
long sleepTime = MIN_SLEEP_TIME + random.nextInt(MAX_SLEEP_TIME - MIN_SLEEP_TIME);
if (female) {
sleepTime += FEMALE_SLEEP_BONUS;
}
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
System.out.println(name + " is done");
}
}

Related

printing alternative output from 2 threads using semaphores

I am learning about the use of semaphores and multi threading in general but am kind of stuck. I have two threads printing G and H respectively and my objective is to alternate the outputs of each thread so that the output string is like this;
G
H
G
H
G
H
Each of the two classes has a layout similar to the one below
public class ClassA extends Thread implements Runnable{
Semaphore semaphore = null;
public ClassA(Semaphore semaphore){
this.semaphore = semaphore;
}
public void run() {
while(true)
{
try{
semaphore.acquire();
for(int i=0; i<1000; i++){
System.out.println("F");
}
Thread.currentThread();
Thread.sleep(100);
}catch(Exception e)
{
System.out.println(e.toString());
}
semaphore.release();
}
}
}
below is my main class
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(1);
ClassA clasA = new ClassA(semaphore);
Thread t1 = new Thread(clasA);
ClassB clasB = new ClassB(semaphore);
Thread t2 = new Thread(clasB);
t1.start();
t2.join();
t2.start();
The output I am getting is way too different from my expected result. can anyone help me please? did I misuse the semaphore? any help?
Semaphores can't help you solve such a task.
As far as I know, JVM doesn't promise any order in thread execution. It means that if you run several threads, one thread can execute several times in a row and have more processor time than any other. So, if you want your threads to execute in a particular order you can, for the simplest example, make a static boolean variable which will play a role of a switcher for your threads. Using wait() and notify() methods will be a better way, and Interface Condition will be the best way I suppose.
import java.io.IOException;
public class Solution {
public static boolean order;
public static void main(String[] args) throws IOException, InterruptedException {
Thread t1 = new ThreadPrint("G", true);
Thread t2 = new ThreadPrint("O", false);
t1.start();
t2.start();
t2.join();
System.out.println("Finish");
}
}
class ThreadPrint extends Thread {
private String line;
private boolean order;
public ThreadPrint(String line, boolean order) {
this.line = line;
this.order = order;
}
#Override
public void run() {
int z = 0;
while (true) {
try {
for (int i = 0; i < 10; i++) {
if (order == Solution.order) {
System.out.print(line + " ");
Solution.order = !order;
}
}
sleep(100);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
}
BTW there can be another problem cause System.out is usually an Operation System buffer and your OS can output your messages in an order on its own.
P.S. You shouldn't inherit Thread and implement Runnable at the same time
public class ClassA extends Thread implements Runnable{
because Thread class already implements Runnable. You can choose only one way which will be better for your purposes.
You should start a thread then join to it not vice versa.
t1.start();
t2.join();
t2.start();
As others have pointed out, locks themselves do not enforce any order and on top of that, you cannot be certain when a thread starts (calling Thread.start() will start the thread at some point in the future, but this might take a while).
You can, however, use locks (like a Semaphore) to enforce an order. In this case, you can use two Semaphores to switch threads on and off (alternate). The two threads (or Runnables) do need to be aware of each other in advance - a more dynamic approach where threads can "join in" on the party would be more complex.
Below a runnable example class with repeatable results (always a good thing to have when testing multi-threading). I will leave it up to you to figure out why and how it works.
import java.util.concurrent.*;
public class AlternateSem implements Runnable {
static final CountDownLatch DONE_LATCH = new CountDownLatch(2);
static final int TIMEOUT_MS = 1000;
static final int MAX_LOOPS = 10;
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
AlternateSem as1 = new AlternateSem(false);
AlternateSem as2 = new AlternateSem(true);
as1.setAlternate(as2);
as2.setAlternate(as1);
executor.execute(as1);
executor.execute(as2);
if (DONE_LATCH.await(TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
System.out.println();
System.out.println("Done");
} else {
System.out.println("Timeout");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdownNow();
}
}
final Semaphore sem = new Semaphore(0);
final boolean odd;
AlternateSem other;
public AlternateSem(boolean odd) {
this.odd = odd;
}
void setAlternate(AlternateSem other) { this.other = other; }
void release() { sem.release(); }
void acquire() throws Exception { sem.acquire(); }
#Override
public void run() {
if (odd) {
other.release();
}
int i = 0;
try {
while (i < MAX_LOOPS) {
i++;
other.acquire();
System.out.print(odd ? "G " : "H ");
release();
}
} catch (Exception e) {
e.printStackTrace();
}
DONE_LATCH.countDown();
}
}

Threading in Sequence

I am trying to learn how to write a program which performs a given set of tasks in sequence with the help of threads. For example, Writing a program which have 3 different threads print 1111…, 22222…., 333333……, so that the output will be 1,2,3,1,2,3,1,2,3…..? OR for e.g. 2 threads one is printing odd numbers and other even numbers, but the output should be printed in sequence - i.e. one even and then odd.
I would like to learn how to write similar kind of programs in which different threads print different stuff concurrently and the output should be printed in sequence.
What is the basic concept in writing these programs. Can we use ThreadPools/Executors for the purpose ? For e.g. can we use
ExecutorService exectorService = Executors.newFixedThreadPool(3);
Can we use Future, FurtureTask, Callable, execute, submit ...? I know these concepts but I am not able to connect the dots for solving the above scenarios.
Please guide me how to go about writing these kind of programs using multithreading / concurrency.
I have written a program using wait()/notifyAll(). Following is the program. I am not executing the consumer as I am printing the whole sequence at the end. Also I am limiting the capacity of the queue to be 15. So I am basically printing the odd / even range till 15.
public class ProduceEven implements Runnable {
private final List<Integer> taskQueue;
private final int MAX_CAPACITY;
public ProduceEven (List<Integer> sharedQueue, int size) {
this.taskQueue = sharedQueue;
this.MAX_CAPACITY = size;
}
#Override
public void run() {
// TODO Auto-generated method stub
int counter = 0;
while (counter < 15) {
try {
produce(counter++);
} catch (InterruptedException e) {
e.getMessage();
}
}
}
private void produce (int i) throws InterruptedException {
synchronized (taskQueue) {
while (taskQueue.size() == MAX_CAPACITY) {
System.out.println("Queue is full : "+Thread.currentThread().getName()+" is waiting , size: "+ taskQueue.size());
taskQueue.wait();
}
Thread.sleep(1000);
if(i%2==0) {
taskQueue.add(i);
}
taskQueue.notifyAll();
}
}
}
public class ProduceOdd implements Runnable {
private final List<Integer> taskQueue;
private final int MAX_CAPACITY;
public ProduceOdd (List<Integer> sharedQueue, int size) {
this.taskQueue = sharedQueue;
this.MAX_CAPACITY = size;
}
#Override
public void run() {
int counter = 0;
while (counter < 15) {
try {
produce(counter++);
} catch (InterruptedException e) {
e.getMessage();
}
}
}
private void produce (int i) throws InterruptedException {
synchronized (taskQueue) {
while (taskQueue.size() == MAX_CAPACITY) {
System.out.println("Queue is full : "+Thread.currentThread().getName()+" is waiting , size: "+ taskQueue.size());
taskQueue.wait();
}
Thread.sleep(1000);
if(i%2==1) {
taskQueue.add(i);
}
taskQueue.notify();
}
}
}
public class OddEvenExampleWithWaitAndNotify {
public static void main(String[] args) {
List<Integer> taskQueue = new ArrayList<Integer>();
int MAX_CAPACITY = 15;
Thread tProducerEven = new Thread(new ProduceEven(taskQueue, MAX_CAPACITY), "Producer Even");
Thread tProducerOdd = new Thread(new ProduceOdd(taskQueue, MAX_CAPACITY), "Producer Odd");
tProducerEven.start();
tProducerOdd.start();
try {
tProducerEven.join();
tProducerOdd.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ListIterator listIterator = taskQueue.listIterator();
System.out.println("Elements Are:: ");
while(listIterator.hasNext()) {
System.out.print(listIterator.next()+" ");
}
}
}
The output which I get is: Elements Are:: 02134657911810131214
The output is all jumbled up. Why is it not in sequence. 01234567891011121314 What am I missing. I would be now trying to make the program using Semaphores. Also how do we make this program using explicit locks?
Yes, you can use ExecutorService as a starting point to run your threads. You can also create and start your Threads manually, that would make no difference.
The important thing is that your Threads will run in parallel if you do not synchronize them (i.e., they have to wait for one another). To synchronize you can, e.g. use Semaphores or other thread communication mechanisms.
You wrote in the comments you have written a producer/consumer program. It's a bit of the same thing. Each time the 1-Thread produces a 1, the 2-Thread must know that it can now produce a 2. When it is finished, it must let the 3-Thread know that it must produce a 3. The basic concepts are the same. Just the threads have both producer and consumer roles.
Hi this is one sample program to print Odd and Even using two thread and using thread synchronization among them.
Also we have used Executor framework which is not mandatory, you can create thread using new Thread() as well. For quick prototype I have used system.exit() which can be replaced with graceful shutdown of threads like, interruption and all.
package com.ones.twos.threes;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class OnesTwos {
public static void main(String[] args) {
BlockingQueue<Integer> bq1 = new ArrayBlockingQueue<Integer>(100);
BlockingQueue<Integer> bq2 = new ArrayBlockingQueue<Integer>(100);
ExecutorService executorService = Executors.newFixedThreadPool(2);
try {
bq1.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.submit(new OddEven(bq1, bq2));
executorService.submit(new OddEven(bq2, bq1));
executorService.shutdown();
}
public static class OddEven implements Runnable {
BlockingQueue<Integer> bq1;
BlockingQueue<Integer> bq2;
public OddEven(BlockingQueue<Integer> bq1, BlockingQueue<Integer> bq2) {
this.bq1 = bq1;
this.bq2 = bq2;
}
#Override
public void run() {
while (true) {
try {
int take = bq1.take();
System.out.println(take);
bq2.offer(take + 1);
if (take > 20)
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Mycode is also similar to Anirban's, except I am not using executor framework,
public class TestThread {
public static void main(String[] args) {
Boolean bol = new Boolean(true);
(new Thread(new Odd(bol), "odd")).start();
(new Thread(new Even(bol), "even")).start();
}
}
public class Even implements Runnable {
private Boolean flag;
public Even(Boolean b) {
this.flag = b;
}
#Override
public void run() {
for (int i = 2; i < 20; i = i + 2) {
synchronized (flag) {
try {
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(1000);
flag.notify();
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Odd implements Runnable {
private Boolean flag;
public Odd(Boolean b) {
this.flag = b;
}
#Override
public void run() {
for (int i = 1; i < 20; i = i + 2) {
synchronized (flag) {
try {
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(1000);
flag.notify();
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
By establishing the thread pool of 3 (ExecutorService exectorService = Executors.newFixedThreadPool(3); you are essentilly limiting the executor capacity to 3 and other incoming threads will be on hold. If you want to run them in paralel you can just submit them at once. If you want to wait for each other and want to find out the result I suggest you use Callable. Personally I really like Callable because after submiting it you can just call the get method of Future, wait for a returned value from the executed thread and then continue to the next one. From the API you can see this:
/**
* Submits a value-returning task for execution and returns a
* Future representing the pending results of the task. The
* Future's {#code get} method will return the task's result upon
* successful completion.
*
*
* If you would like to immediately block waiting
* for a task, you can use constructions of the form
* {#code result = exec.submit(aCallable).get();}
And a very good example here. If you go for the Callable alternative then you don't need a Thread pool. Just a normal executor is fine. Remember to shut the executor down in the end.
class MyNumber {
int i = 1;
}
class Task implements Runnable {
MyNumber myNumber;
int id;
Task(int id, MyNumber myNumber) {
this.id = id;
this.myNumber = myNumber;
}
#Override
public void run() {
while (true) {
synchronized (myNumber) {
while (myNumber.i != id) {
try {
myNumber.wait(); //Wait until Thread with correct next number
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(id);
if (myNumber.i == 1) {
myNumber.i = 2;
} else if (myNumber.i == 2) {
myNumber.i = 3;
} else {
myNumber.i = 1;
}
myNumber.notifyAll();
}
}
}
}
In main method:
MyNumber myNumber = new MyNumber();
new Thread(new Task(1, myNumber)).start();
new Thread(new Task(2, myNumber)).start();
new Thread(new Task(3, myNumber)).start();
Hi here we have used 2 thread one to print even and another to print odd.
Both are separate and have no relation to each other.
But we have to do a synchronization mechanism between them. Also we need a mechanism to let the ball rolling, i.e. start one thread printing.
Each thread is waiting on condition and after doing it's task it lets other thread work and put ownself in waiting state.
Well happy path works fine, but we need special care when even thread is not in waiting state and the signal() from main fires, in that case even thread will never able to wake up and the program hangs.
So to make sure main thread successfully sends a signal() to even thread and even thread does not miss that we have used Phaser(with party) and checking even thread state in while loop in main.
Code is as below.
package com.ones.twos.threes;
import java.util.concurrent.Phaser;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class OnesTwosTrial2 {
public static void main(String[] args) {
Lock lk = new ReentrantLock();
Phaser ph = new Phaser(3); // to let main start the even thread
Condition even = lk.newCondition();
Condition odd = lk.newCondition();
OnesTwosTrial2 onestwostrial2 = new OnesTwosTrial2();
Thread ev = onestwostrial2.new Evens(lk, even, odd, ph);
Thread od = onestwostrial2.new Odds(lk, even, odd, ph);
ev.start();
od.start();
System.out.println("in main before arrive");
ph.arriveAndAwaitAdvance();
System.out.println("in main after arrive");
// we have to make sure odd and even thread is
// started and waiting on respective condition.
// So we used Phaser with 3, because we are having here
// 3 parties (threads)
// main, odd,even. We will signal only when all the
// threads have started.
// and waiting on conditions.
while (!Thread.State.WAITING.equals(ev.getState())) {
System.out.println("waiting");
}
lk.lock();
even.signal();
lk.unlock();
}
class Evens extends Thread {
Lock lk;
Condition even;
Condition odd;
Phaser ph;
public Evens(Lock lk, Condition even, Condition odd, Phaser ph) {
this.lk = lk;
this.even = even;
this.odd = odd;
this.ph = ph;
}
#Override
public void run() {
System.out.println("even ph");
int cnt = 0;
while (cnt < 20) {
try {
lk.lock();
ph.arrive();
even.await();
System.out.println(cnt);
cnt += 2;
odd.signal();
lk.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Odds extends Thread {
Lock lk;
Condition even;
Condition odd;
Phaser ph;
public Odds(Lock lk, Condition even, Condition odd, Phaser ph) {
this.lk = lk;
this.even = even;
this.odd = odd;
this.ph = ph;
}
#Override
public void run() {
System.out.println("odd ph");
int cnt = 1;
while (cnt < 20) {
try {
lk.lock();
ph.arrive();
odd.await();
System.out.println(cnt);
cnt += 2;
even.signal();
lk.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

Sleeping threads in JAVA

I am currently working on a project where I am to have essentially 10 threads that are "sleeping". At random one of these 10 threads is to "wake up" and start doing some work. I just want to see if I am headed in the right direction. So should I just create each instance of the thread for instance.
Thread thread0 = new Thread(new doWork());
...
Thread thread9 = new Thread(new doWork());
and just not start them and then when they are to "wake" just call the start() method on the particular thread..
or should I start each thread but have them wait() until I call the notify() method?
or should I start the thread and use sleep() and then call the interrupt() method?
Which approach seems to be better and why?
Any insight is greatly appreciated.
edit Will this be acceptable??
import java.util.Random;
public class Client {
private static Thread [] clients = new Thread[10];
public static void main(String[] args){
createClients();
randomWake();
}// end main()
static void createClients(){
Thread client0 = new Thread(new ClientThread(0));
clients[0] = client0;
Thread client1 = new Thread(new ClientThread(1));
clients[1] = client1;
Thread client2 = new Thread(new ClientThread(2));
clients[2] = client2;
Thread client3 = new Thread(new ClientThread(3));
clients[3] = client3;
Thread client4 = new Thread(new ClientThread(4));
clients[4] = client4;
Thread client5 = new Thread(new ClientThread(5));
clients[5] = client5;
Thread client6 = new Thread(new ClientThread(6));
clients[6] = client6;
Thread client7 = new Thread(new ClientThread(7));
clients[7] = client7;
Thread client8 = new Thread(new ClientThread(8));
clients[8] = client8;
Thread client9 = new Thread(new ClientThread(9));
clients[9] = client9;
for(int i = 0; i < clients.length; i++)
clients[i].start();
}// end createClients()
static void randomWake(){
Random rand = new Random();
int randomNumber = rand.nextInt(10);
clients[randomNumber].interrupt();
}// end randomWake()
static class ClientThread implements Runnable{
private int clientNumber;
public ClientThread(int clientNumber){
this.clientNumber = clientNumber;
}// end ClientThread(int clientNumber)
public void run(){
while(!Thread.interrupted()){}
System.out.println("Client " + clientNumber + " is awake!");
}// end run()
}// end class ClientThread
}// end class Client
In case there is a maximum amount of sleep time
You probably will need to implement the following Thread class:
public class DoWork extends Thread {
public void run () {
while(true) {
Thread.Sleep((int) Math.floor(Math.random()*10000));
//do some work
}
}
}
Where 10000 is the maximum time in milliseconds a thread should sleep.
In case there is no maximum amount of sleep time
You probably will need to implement the following Thread class:
public class DoWork extends Thread {
public void run () {
while(true) {
Thread.Sleep(1);
if(Math.random() < 0.005d) {
//do some work
}
}
}
}
where 0.005 is the probability of running the method a certain millisecond.
notify and wait are used to implement Semaphores: this are objects that prevent two threads to manipulate the same object at the same time (since some objects could end up in an illegal state).
How about using semaphores?
class DoWork extends Runnable {
private final Semaphore semaphore;
DoWork(Semaphore semaphore) {
this.semaphore = semaphore;
}
#Override
public void run() {
while (true) {
semaphore.acquire();
//do some work
}
}
}
The main program can create an array of Semaphores, and an equal number of Threads running DoWork instances, so that each DoWork instance has its own semaphore. Each time the main program calls sema[i].release(), The run() method of the corresponding DoWork instance will "do some work" and then go back to waiting.
It doesn't make much sense your answer, so not sure what you really want to achieve. But for what you describe you should put all threads waiting on the same lock and just notify the lock (it will awake only one randomly)
But as that doesn't make much sense, I guess you want to achieve something different.
Check this question regarding sleep vs wait: Difference between wait() and sleep()
Check this one. This is how I would solve it if I were not to use ThreadPooling (which is very correct as the others have said) and so that I can see how wait(),notify() and Thread.sleep() work. Checking google you will see (e.g. Thread.sleep and object.wait) that the mainly wait() and notify() are used for communication between threads and Thread.sleep is used so that you can pause your program.
-Part of this answer is based on this: http://tutorials.jenkov.com/java-concurrency/thread-signaling.html#missedsignals. You can check in the code to see the steps that you need to take (comment out some parts of the code) in order to make your program hang, so that you realize how to work with missed signals. The iterations needed for your program to hang are not fixed.
-The programm will run forever. You will need to work on it a bit in order to fix that.
Main
public class Main
{
public static void main(String[] args)
{
Manager mgr = new Manager("manager");
mgr.start();
}
}
Manager
public class Manager extends Thread
{
private final Object lock = new Object();
private boolean wasSignalled = false;
private DoWork[] workThreads = new DoWork[5];
public Manager(String name){
super(name);
workThreads[0] = new DoWork(this,"work 0");
workThreads[1] = new DoWork(this,"work 1");
workThreads[2] = new DoWork(this,"work 2");
workThreads[3] = new DoWork(this,"work 3");
workThreads[4] = new DoWork(this,"work 4");
}
public void wakeUP()
{
synchronized (this.lock) {
wasSignalled = true;
this.lock.notify();
}
}
public void pauseAndWait()
{
synchronized (this.lock) {
if(!wasSignalled)
{
try {
this.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//clear signal and continue running.
wasSignalled = false;
}
}
public void run ()
{
int i=0;
while(true)
{
i++;
System.out.println(" manager ...: "+i+" ");
int choose = 0 + (int)(Math.random() * ((4 - 0) + 1));
//choose=0; for debugginng
if(!workThreads[choose].isAlive()){
workThreads[choose].start();
}
else{
workThreads[choose].wakeUP();
}
//wait to be notified by DoWork thread when its job
//is done
pauseAndWait();
}
}
}
DoWork
public class DoWork extends Thread
{
private final Object lock = new Object();
private boolean wasSignalled = false;
private Manager managerThread;
public DoWork(Manager managerThread,String name){
super(name);
this.managerThread=managerThread;
}
public void wakeUP()
{
synchronized (this.lock) {
//check what happens without wasSignalled flag
//step #1: comment out wasSignalled = true;
wasSignalled = true;
this.lock.notify();
}
}
public void pauseAndWait()
{
synchronized (this.lock) {
//check what happens without wasSignalled flag
//step #2: comment out the if block
if(!wasSignalled)
{
try {
this.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//check what happens without wasSignalled flag
//step #3: comment out wasSignalled = false;
//clear signal and continue running.
wasSignalled = false;
}
}
public void run ()
{
int i=0;
while(true)
{
i++;
try {
System.out.print(this.getName()+" going to sleep ...: "+i+" ");
//check what happens without wasSignalled flag
//step #4: put sleep time to Thread.sleep(0);
//simulate worker thread job
Thread.sleep(1000);
System.out.println(" woke up ... ");
} catch (InterruptedException e) {
System.out.println(" worker thread: job simulation error:"+e);
}
//if worker thread job simulation is done (sleep for 4 times)
//then suspend thread and wait to be awaken again
if(i>4)
{
System.out.println(this.getName()+" notifying main ...: "+i+" \n");
i=0;
managerThread.wakeUP();
// thread does not get destroyed, it stays in memory and when the manager
// thread calls it again it will wake up do its job again
pauseAndWait();
}
}
}
}

Java Threads Synchronizing Problem

I have the following 2 classes code that produce this result for instance:
Wainting for calculation to complete...
Calculator thread says HELLO!
T1 says that total is 10
Wainting for calculation to complete...
Wainting for calculation to complete...
Now threads are waiting but nobody is going to notify them.
How can I force the threads from T1 to T3 to run before the "Calculator thread" wake em up?
public class Calculator implements Runnable{
private int total;
public int getTotal() {
return total;
}
#Override
public void run() {
synchronized (this) {
for (int i = 0; i < 5; i++) {
total += i;
}
System.out.println(Thread.currentThread().getName() + " says HELLO!");
notifyAll();
}
}
}
import static java.lang.System.out;
public class Reader implements Runnable{
private Calculator c;
public Reader(Calculator calc) {
c = calc;
}
public Calculator getCalculator() {
return c;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
Reader read = new Reader(calc);
Thread thread1 = new Thread(read);
Thread thread2 = new Thread(read);
Thread thread3 = new Thread(read);
thread1.setName("T1");
thread2.setName("T2");
thread3.setName("T3");
thread1.start();
thread2.start();
thread3.start();
Thread calcThread = new Thread(read.getCalculator());
calcThread.setName("Calculator thread");
calcThread.start();
}
}
#Override
public void run() {
synchronized (c) {
try {
out.println("Wainting for calculation to complete...");
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
out.println(Thread.currentThread().getName() + " says that " + "total is " + c.getTotal());
}
}
}
This is how I would write the code. Rather than trying to re-invent the wheel with wait/notify I would use concurrency library to do what is needed, a Future.
import java.util.concurrent.*;
public class Main {
static final long start = System.nanoTime();
static void log(String text) {
double seconds = (System.nanoTime() - start) / 1e9;
System.out.printf("%s %.6f - %s%n", Thread.currentThread().getName(), seconds, text);
}
static class Calculator implements Callable<Integer> {
#Override
public Integer call() throws Exception {
int total = 0;
log("calculating total");
for (int i = 0; i < 50000; i++)
total += i;
log("total is " + total);
return total;
}
}
static class Reader implements Callable<Void> {
private final Future<Integer> totalFuture;
public Reader(Future<Integer> totalFuture) {
this.totalFuture = totalFuture;
}
#Override
public Void call() throws ExecutionException, InterruptedException {
log("Waiting for total.");
int total = totalFuture.get();
log("... got total= " + total);
return null;
}
}
public static void main(String... args) {
ExecutorService es = Executors.newCachedThreadPool();
Future<Integer> totalFuture = es.submit(new Calculator());
es.submit(new Reader(totalFuture));
es.submit(new Reader(totalFuture));
es.submit(new Reader(totalFuture));
es.shutdown();
}
}
prints
pool-1-thread-1 0.008154 - calculating total
pool-1-thread-4 0.011356 - Waiting for total.
pool-1-thread-3 0.011292 - Waiting for total.
pool-1-thread-2 0.011128 - Waiting for total.
pool-1-thread-1 0.025097 - total is 1249975000
pool-1-thread-4 0.025351 - ... got total= 1249975000
pool-1-thread-3 0.025372 - ... got total= 1249975000
pool-1-thread-2 0.025380 - ... got total= 1249975000
After
thread3.start();
add the following to wait for the threads to finish.
thread1.join();
thread2.join();
thread3.join();
Thread.join() may seem like an option in this particular situation. Since you have control of the main() function and you know exactly when each thread is starting.
A more general way to handle this situation is use a conditional variable and call the c.wait() within a loop to check the condition variable.
Basically add the isFinished field in the Calculator class :
public class Calculator implements Runnable {
...
public volatile boolean isFinished = false
..
..
Then you replace c.wait() with :
...
while (!c.isFinished) {
c.wait();
}
...
Finally in the `run() method of your Calculator class after calculating total, set the isFinished field
....
for(int i = 0; ....
total = += i;
}
c.isFinished = true
....
U may use Thread.join() method.. I'm not sure how abouts of good programming practices but that will work..

Java Concurrency: Exclusive Queue Problem

I am trying to write a solution for 'Exclusive Queue' problem from 'Little book of Semaphores'.
Problem is stated as follows:
Imagine that threads represent ballroom dancers and that two kinds of dancers, leaders and followers, wait in two queues before entering the dance floor. When a leader arrives, it checks to see if there is a follower waiting. If so, they can both proceed. Otherwise it waits. Similarly, when a follower arrives, it checks for a leader and either proceeds or waits, accordingly. Also, there is a constraint that each leader can invoke dance concurrently with only one follower, and vice versa.
Book mentions it's solution using semaphores, but I am trying to solve it using Object lock in Java. Here is my solution:
ExclusiveQueuePrimitive.java:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ExclusiveQueuePrimitive {
public static void main(String[] args) throws InterruptedException {
System.out
.println("-------------------------------Application START-------------------");
final int NUM_RUN = 1000;
// for (int j=0; j<NUM_RUN; j++) {
for (;;) {
Counters c = new Counters();
int NUM_THREADS = 5;
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < NUM_THREADS; i++) {
Thread tl = new Thread(new Leader(c, i + 1));
Thread tf = new Thread(new Follower(c, i + 1));
threads.add(tf);
threads.add(tl);
tf.start();
tl.start();
}
for (int i = 0; i < threads.size(); i++) {
Thread t = threads.get(i);
t.join();
}
}
// System.out.println("--------------------------------Application END-------------------");
}
}
class Counters {
public int leaders = 0;
public int followers = 0;
//public final Lock countMutex = new ReentrantLock();
public boolean printed = false;
public Lock printLock = new ReentrantLock();
public final Lock leaderQueue = new ReentrantLock();
public final Lock followerQueue = new ReentrantLock();
public void dance(String str) {
System.out.println("" + str);
}
public void printLine() {
System.out.println("");
}
}
class Leader implements Runnable {
final Counters c;
final int num;
public Leader(Counters counters, int num) {
this.c = counters;
this.num = num;
}
#Override
public void run() {
synchronized (c.leaderQueue) {
try {
if (c.followers > 0) {
c.followers--;
synchronized (c.followerQueue) {
c.followerQueue.notify();
}
} else {
c.leaders++;
c.leaderQueue.wait();
}
c.dance("Leader " + num + " called dance");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Follower implements Runnable {
final Counters c;
final int num;
public Follower(Counters counters, int num) {
this.c = counters;
this.num = num;
}
#Override
public void run() {
synchronized (c.followerQueue) {
try {
if (c.leaders > 0) {
synchronized (c.leaderQueue) {
c.leaders--;
c.leaderQueue.notify();
}
} else {
c.followers++;
c.followerQueue.wait();
}
c.dance("Follower " + num + " called dance");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
However, after running for a while, it hangs up. Can you tell me where is the deadlock and how I can fix it. Also, i want print a new line after pair of Leader and Follower are done. How can I do that?
That IS a classic deadlock:
class Leader {
synchronized (c.leaderQueue) { ...
synchronized (c.followerQueue) { ... }
}
}
class Follower {
synchronized (c.followerQueue) { ...
synchronized (c.leaderQueue) { ... }
}
}
The simplest thing to prevent that is to grab the locks in the same order (btw using Lock and synchronized together is not a good practice). There are other techniques to detect deadlocks, but in the context of your task it should be more beneficial to change the algorithm.
Start simple - use single lock to make the logic correct, then do more smart things to improve concurrency without breaking correctness.
You have a mutex on c.followerQueue and one on c.leaderQueue. On one side you acquire the leader queue first and then the follower queue, and on the other side you acquire the follower queue first.
This is bad. If one side grabs the follower lock, and the other side grabs the leader lock, then neither can proceed. You must avoid having inconsistent orderings of lock acquisitions.
To print a line after each pair finishes, just print in either the leader or the follower but not both. The code for the leader finishing implies a follower has finished also...

Categories

Resources