Multiple threads in Java - java

I am currently working on modified version of Cigarette Smoker problem. Below you can find my agent class. What I need to do in order to have three threads instead of one? So there will be three outputs instead of one.
public class agent extends Thread {
private table smokingtable;
public agent(table pSmokingtable)
{
smokingtable = pSmokingtable;
}
#Override
public void run()
{
while(true)
{
try {
Thread.sleep(5000);
} catch (Exception e) {}
smokingtable.setAgentElements();
// this triggers the smoker-threads to look at the table
output("The Agent puts " + smokingtable.getAgentElements() + table.");
// pause the agent while one smoker thread is running
}
}
public synchronized void wake()
{
try
{
notify();
} catch(Exception e){}
}
public synchronized void pause()
{
try
{
this.wait();
} catch (Exception e) {}
}
private void output(String pOutput)
{
System.out.println(pOutput);
}
}
I have done something like this but surely this is wrong.
public class agent extends Thread {
private table smokingtable;
public agent(table pSmokingtable)
{
smokingtable = pSmokingtable;
}
#Override
public void run()
{
while(true)
{
try {
Thread.sleep(5000);
} catch (Exception e) {}
smokingtable.setAgent1Elements();
output("The Agent 1 puts " + smokingtable.getAgent1Elements());
smokingtable.setAgent2Elements();
output("The Agent 2 puts " + smokingtable.getAgent2Elements());
smokingtable.setAgent3Elements();
output("The Agent 3 puts " + smokingtable.getAgent3Elements());
pause();
}
}
public synchronized void wake()
{
try
{
notify();
} catch(Exception e){}
}
public synchronized void pause()
{
try
{
this.wait();
} catch (Exception e) {}
}
private void output(String pOutput)
{
System.out.println(pOutput);
}
}

In order to have 3 threads instead of 1 you need to create 3 threads and start them.
In your case, the simplest approach is this:
Thread agent1 = new agent( );
Thread agent2 = new agent( );
Thread agent3 = new agent( );
agent1.start( );
agent2.start( );
agent3.start( );
agent1.join( );
agent2.join( );
agent3.join( );
Better way of doing things would be to use ExecutorService framework, e.g. ThreadPoolExecutor.
ExecutorService pool = Executors.newFixedThreadPool( 3 );
for ( int i = 0; i < 3; ++i )
{
pool.execute( new agent( ) );
}
// This will wait for your agents to execute
pool.shutdown( );

Maybe I completely misunderstood your question, but it looks like you need to review again the basics of working with treads in java. this would be a good place to start
In the second example it looks like you are trying to run all three agents from the same thread, and i guess this is not what you intended to do.
In the first code extract you gave, add an agent id as field and to the agent's constructor, and append this Id to the output message.
now all you need to do is to create three agent instances from somewhere (probably your main method) and call their run method from there.
public static void main(String[] args) {
for(int i = 0; i < 3; i++)
new agent(i).start();
}
have a look at this simple example

Related

Java - two threads with wait() and notify()

I am new to Java programming. i want to run two threads using wait() and notify(). But I cant use task flags for thread synchronization,sleep, yield or wait(parameter).I wrote it, but i had to use sleep. can someone help me to change it to without sleep.
This is my main class
public class mainClass{
public static void main(String args[]) throws InterruptedException {
final Processor processor = new Processor();
for(int i=0; i<100; i++){
final int z = i;
Thread trainer = new Thread(new Runnable(){
public void run(){
try{
processor.produce(z);
}catch(InterruptedException e){
e.printStackTrace();
}
}
});
Thread sportsman = new Thread(new Runnable(){
public void run(){
try{
processor.consume(z);
}catch(InterruptedException e){
e.printStackTrace();
}
}
});
trainer.start();
sportsman.start();
trainer.join();
sportsman.join();
}
System.out.println("100 Tasks are Finished.");
}
}
this is my second class.
public class Processor {
public void produce(int n) throws InterruptedException {
synchronized (this){
System.out.println("Trainer making " + (n+1) + " Task..." );
wait();
System.out.println("");
}
}
public void consume(int m) throws InterruptedException {
Thread.sleep(1);
//I want to run the code without using sleep and get same output
synchronized (this){
System.out.println("Sportman doing " + (m+1) + " Task...");
notify();
}
}
}
this is my output.
Trainer making 1 Task...
Sportman doing 1 Task...
Trainer making 2 Task...
Sportman doing 2 Task...
.
.
.
Trainer making 99 Task...
Sportman doing 99 Task...
Trainer making 100 Task...
Sportman doing 100 Task...
100 Tasks are Finished.
thank you. my english is bad. sorry for it.
Hints:
The correct use of wait involves waiting for something specific to happen. The correct implementation is something like this
synchronize (x) {
while (!x.itHasHappened()) {
x.wait(); // for it to happen
}
}
The loop is necessary since it is possible to get spurious notifies on a primitive lock.
In your specific example, ask yourself what must wait for what to happen. I think you've got it wrong. What is produce(N) actually waiting for, and why?
In mainClass you created 100 times two threads, I think you should create two threads only and in those two threads run the loop 100 times.
Probably you needed to do something like this...
The producer should create together 100 task (one at a time) and wait after each task for the consumer to be done.
The consumer should wait for a task and notify the producer when finished with the current task, them wait for the next task.
So your mainClass should look like this, loops should be in the producer() and consumer() methods.
public class mainClass {
public static void main(String args[]) throws InterruptedException {
final Processor processor = new Processor();
Thread trainer = new Thread(new Runnable() {
public void run() {
try {
processor.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread sportsman = new Thread(new Runnable() {
public void run() {
try {
processor.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
trainer.start();
sportsman.start();
trainer.join();
sportsman.join();
System.out.println("100 Tasks are Finished.");
}
}
And the Processor maybe something like this...
public class Processor {
private int taskNo = 0; // the number of the current task
// (0 = there is no task, but will be)
// (-1 = there won't be more task)
public void produce() throws InterruptedException {
synchronized (this) {
for (int i = 0; i < 100; i++) {
taskNo = i + 1; // making a task number (i+1)
System.out.println("Trainer making " + taskNo + " Task...");
notify(); // notifies the consumer that the task was made
wait(); // and waiting the consumer to finish... zzzz...
System.out.println("");
}
taskNo = -1; // there will be no more task
notify(); // notify the consumer about it
}
}
public void consume() throws InterruptedException {
synchronized (this) {
do {
if (taskNo == 0) {
wait(); // there is no task to do, waiting... zzzz...
}
if (taskNo != -1) {
System.out.println("Sportman doing " + taskNo + " Task...");
taskNo = 0; // sets the task to done
notify(); // notifies the producer that the task was done
}
} while (taskNo != -1);
}
}
}
Typically there is a queue instead of the taskNo variable, where the producer puts tasks and the consumer takes tasks from in. But in your case the queue can have only 1 task at a time, because the producer should wait for the consumer to finish. So you can use a simple variable (taskNo) instead of a queue.

How to make two threads wait and notify each other

I have to create two Threads which have to poll and object from a queue in 2 seconds intervals.
The first Thread poll and object then wait and notify the second one to poll the object from it's queue.
I read all about wait and notify but nothing works with me.
Any sugestions?
First thread:
public class SouthThread extends Thread {
private Queue<Car> q = new LinkedList<Car>();
public void CreateQueue() {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
Car c = new Car();
System.out.println("Enter registration number: ");
String regNum = input.nextLine();
c.setRegNum(regNum);
q.offer(c);
}
}
public int getQueueSize() {
return q.size();
}
#Override
public void run() {
while (q.size() != 0)
try {
while (q.size() != 0) {
synchronized (this) {
System.out.print("The car with registration number: ");
System.out.print(q.poll().getRegNum());
System.out
.println(" have passed the bridge from the south side.");
this.wait(2000);
notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Second thread:
public class NorthThread extends Thread {
private Queue<Car> q = new LinkedList<Car>();
public void CreateQueue() {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
Car c = new Car();
System.out.println("Enter registration number: ");
String regNum = input.nextLine();
c.setRegNum(regNum);
q.offer(c);
}
}
public int getQueueSize() {
return q.size();
}
#Override
public void run() {
try {
while (q.size() != 0) {
synchronized (this) {
System.out.print("The car with registration number: ");
System.out.print(q.poll().getRegNum());
System.out
.println(" have passed the bridge from the north side.");
this.wait(2000);
notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Main Thread:
public class Main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
SouthThread tSouthThread = new SouthThread();
NorthThread tNorthThread = new NorthThread();
tSouthThread.CreateQueue();
tNorthThread.CreateQueue();
System.out.println(tSouthThread.getQueueSize());
tSouthThread.start();
tNorthThread.start();
}
}
It seems that what you basically want to achieve is a system that alternates control between two independent units so that each of the units gets some time to process followed by a two second waiting period (or vice versa).
There are two main ways you could achieve this:
Using a central control
With autonomous communicating agents
The first approach is a bit easier. Here, you have a central "master" component which takes care of coordinating who gets the processing time and also implements the wait times. For that approach, the two independent units do not even have to be Threads:
public class South {
private Queue<Car> q = new LinkedList<Car>();
public void CreateQueue() { ... }
public void poll() {
System.out.print("The car with registration number: ");
System.out.print(q.poll().getRegNum());
System.out.println(" have passed the bridge from the South side.");
}
}
public class North {
private Queue<Car> q = new LinkedList<Car>();
public void CreateQueue() { ... }
public void poll() {
System.out.print("The car with registration number: ");
System.out.print(q.poll().getRegNum());
System.out.println(" have passed the bridge from the North side.");
}
}
// This is the "master" class
public class Main {
public static void main(String[] args) {
South south = new South();
North north = new North();
south.CreateQueue();
north.CreateQueue();
boolean done = false;
while (!done) {
try {
Thread.sleep(2000);
} (catch InterruptedException) { /* TODO */ }
north.poll();
try {
Thread.sleep(2000);
} (catch InterruptedException) { /* TODO */ }
south.poll();
}
}
}
Note that North and South do not inherit from Thread here, i.e., they are just plain old objects.
(However, if your program is more complex and North/South are only one part of it, you might want to make Main(!) a separate thread and put the above while-loop inside the thread's run method, so that the rest of the program can run concurrently.)
In the second approach, you don't have such a central control component, but the both North and South run in their own separate threads. This then requires that they coordinate who's allowed to process by communicating with each other.
public class SouthThread extends Thread {
protected Queue<Car> q = new LinkedList<Car>();
protected North north;
public void CreateQueue() { ... }
public void poll() { ... }
public void run() {
boolean done = false;
while (!done) {
// wait two seconds
try {
Thread.sleep(2000);
} (catch InterruptedException) { /* TODO */ }
// process one element from the queue
poll();
// notify the other thread
synchronized (north) {
north.notifyAll();
}
// wait until the other thread notifies this one
try {
synchronized (this) {
wait();
}
} (catch InterruptedException) { /* TODO */ }
}
}
}
public class NorthThread extends Thread {
protected Queue<Car> q = new LinkedList<Car>();
protected South south;
public void CreateQueue() { ... }
public void poll() { ... }
public void run() {
boolean done = false;
while (!done) {
// wait two seconds
try {
Thread.sleep(2000);
} (catch InterruptedException) { /* TODO */ }
// process one element from the queue
poll();
// notify the other thread
synchronized (south) {
south.notifyAll();
}
// wait until the other thread notifies this one
try {
synchronized (this) {
wait();
}
} (catch InterruptedException) { /* TODO */ }
}
}
}
public class Main {
public static void main(String[] args) throws Exception {
SouthThread tSouthThread = new SouthThread();
NorthThread tNorthThread = new NorthThread();
tSouthThread.north = tNorthThread;
tNorthThread.south = tSouthThread;
tSouthThread.CreateQueue();
tNorthThread.CreateQueue();
tSouthThread.start();
tNorthThread.start();
}
}
A more general remark: since both North and South seem to be doing basically the same, there's probably no need to implement them in two separate classes. Instead, it should be sufficient to have only one class that implements the desired functionality and instantiate it twice:
// We can combine the functionality of North and South
// in a single class
public class NorthSouth {
public void CreateQueue() { ... }
public void poll() { ... }
// etc.
}
public class Main {
public static void main(String[] args) {
NorthSouth north = new NorthSouth();
NorthSouth south = new NorthSouth();
north.CreateQueue();
south.CreateQueue();
// etc.
}
}
wait and notify must refer to the same lock: When you call object.wait(2000) what you're saying is "I'm going to wait here for 2000 millis, or until someone else calls object.notify() where object refers to me"
I still don't completely understand what you want to achieve, but if you simply want two threads that concurrently do:
Do something
Wait 2 seconds
GOTO 1
then you don't need wait/notify at all, you could get around using Thread.sleep() or potentially two instances of java.util.Timer.
But again, I'm not sure I understand correctly. :-(

getting thread names in stop() method

how can I get in stop() thread names like i did in start()? Thread names are A,B,C,D. My program runs thread in order and stops them in revers order. But I have problem with printing their names. In start() I do it without any problems but in stop() I just dont know how to do it. I'm pretty new in java and this is one of my firs programs that I did that is why i dont know how to do this.
Thank you so much for your help.
Here is the code:
import java.util.*;
class Service extends Thread
{
private RobotController controller;
public String robotID;
private byte[] lock;
public Service(RobotController cntrl, String id)
{
controller = cntrl;
robotID = id;
}
public byte[] getLock() { return lock;}
public void run()
{
lock = new byte[0];
synchronized(lock)
{
byte[] data;
while ((data = controller.getData()) == null)
{
try {
lock.wait();
} catch (InterruptedException ie) {}
}
System.out.println("Thread " + robotID + " Working" );
}
}
}
class RobotController
{
private byte[] robotData;
private Vector threadList = new Vector();
private Service thread_A;
private Service thread_B;
private Service thread_C;
private Service thread_D;
public void setup(){
thread_A = new Service(this, "A");
thread_B = new Service(this, "B");
thread_C = new Service(this, "C");
thread_D = new Service(this, "D");
threadList.addElement(thread_A);
threadList.addElement(thread_B);
threadList.addElement(thread_C);
threadList.addElement(thread_D);
thread_A.start();
thread_B.start();
thread_C.start();
thread_D.start();
start();
stop();
}
public void start()
{
System.out.println("START:");
{
for (int i=0; i <threadList.size(); i++)
{
try {
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie);
}
putData(new byte[10]);
Service rbot = (Service)threadList.elementAt(i);
byte[] robotLock = rbot.getLock();
synchronized(robotLock) {
robotLock.notify();
}
}
}
}
public void stop()
{
Collections.reverse(threadList);
System.out.println("STOP:");
for ( Object o : threadList) {
System.out.println("Thread "+ o +" Stop");
}
}
public synchronized byte[] getData()
{
if (robotData != null)
{
byte[] d = new byte[robotData.length];
System.arraycopy(robotData, 0, d, 0, robotData.length);
robotData = null;
return d;
}
return null;
}
public void putData(byte[] d) { robotData = d;}
public static void main(String args[])
{
RobotController controller = new RobotController();
controller.setup();
}
}
Thread has name and getter getName(), so if you have instance of thread you can always call thread.getName().
I do not know how do you access the thread name "in start" because I do not see where do you call getName(). However I think I know what's your problem in stop.
You store your threads in Vector. Then you iterate over vector's elements and print thread, so it invokes thread's toString(). You probably have to cast Object to Thread and call its getName():
System.out.println("STOP:");
for ( Object o : threadList) {
System.out.println("Thread "+ ((Thread)o).getName() +" Stop");
}
But once you are done, I'd recommend you to find a good and new enough tutorial on java.
You are using not commonly applicable coding formatting.
You are using Vector instead of List and its implementations.
You are trying to use unclear technique for thread synchronization and management.
Start learning step-by-step. And do not hesitate to ask questions. Good luck.

Java wait specific interval notify not working

Code snippet:
class Counter implements Runnable {
Object s = new Object();
#Override
public void run() {
try {
synchronized (s) {
s.wait(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
//...do Something
}
public void stopCounter() {
synchronized (s) {
s.notifyAll();
}
}
}
Irrespective of whether i call stopCounter or not, the ...do Something code always executes only after the wait interval. Even after notify it still waits for 10 secs.
I cannot tell from your example what you are trying to achieve. If it is to try and replace some sort of polling then consider the BlockingQueue interface that was released in Java 5. Since that has appeared I have had no need for wait/notify. It's a lot more simple to use and java behind the scenes does the equivalent of the wait/notify for you.
It depends of the way you use it. I have just tried it by adding a main method and running it and it seems like the wait / notify mechanism is working fine, not the way you described it. Please try it yourself:
public static void main(String[] args) {
Counter c = new Counter();
new Thread(c).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.stopCounter();
}
My guess is that you call the run and stopCounter methods on different instances of your Counter class. They therefore use different monitors (your s = new Object()) and the call to stop won't notify the other Counter.
For example, this would behave similarly to what you describe (unless you get a spurious wakeup):
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
new Thread(c).start();
Thread.sleep(200);
new Counter().stopCounter();
}
static class Counter implements Runnable {
Object s = new Object();
#Override
public void run() {
try {
System.out.println("in");
synchronized (s) {
s.wait(10000);
}
System.out.println("out");
} catch (InterruptedException e) {
e.printStackTrace();
}
//...do Something
}
public void stopCounter() {
synchronized (s) {
s.notifyAll();
}
System.out.println("notified");
}
}

How to solve this thread blocking issue

I'm testing a Java multi-threading sample code but the thread started in the for loop of qB.start() is blocked because it's waiting for entry of qB monitor. What is the cause of this blockage?
Thank you.
import java.util.*;
class QA {
public synchronized void open() throws Exception {
Thread o = new Thread() {
public void run() {
QB qB = new QB();
qB.start();
}
};
o.start();
}
public static void main(String args[]) throws Exception {
new QA().open();
}
public class QB {
private boolean shutdown;
private Vector<Thread> tList;
private final Object waitingLock = new Object();
public QB() {
tList = new Vector<Thread>();
}
public synchronized void start() {
for(int i = 0; i < 1; i++) {
final int id = i;
Thread t = new Thread("Thread " + id) {
public void run() {
load(id);
}
};
tList.add(i, t);
t.start();
}
tMonitor();
waitUntilFinished();
}
private void tMonitor() {
Thread cmt = new Thread("T Monitor Thread") {
public void run() {
synchronized(waitingLock) {
while(tList.size() > 0) {
try {
sleep(10000);
} catch(Exception e) {
e.printStackTrace();
}
}
waitingLock.notifyAll();
}
}
};
cmt.start();
}
private void waitUntilFinished() {
synchronized(waitingLock) {
while(!isShutDown()) {
try {
waitingLock.wait();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
private synchronized void load(int id) {
try {
System.out.println("blocked here");
// some work done here
removeFromTList(id);
} catch(Exception e) {
e.printStackTrace();
}
}
public synchronized boolean isShutDown() {
return shutdown;
}
}
}
The first problem I see is that QB#start() is synchronized on the instance of QB.
Inside the thread t that you are trying to spawn, load(id) is also synchronized on the same instance of QB. So when you call t.start() the t thread blocks until QB#start() finishes.
Presumably, at the end of the QB#start() method, QB#waitUntilFinished() is supposed to wait for all the t threads to finish, but they can't even enter the QB#load method because they're still waiting for the QB#start() method to release the lock on the QB instance.
So, circular deadlock.
Edit:
Ok, now that we see how the threads are removed from tList the bug is fully revealed.
If the index 0 thread finishes first then it will remove itself from the list. That means when the index 1 thread finishes, it will remove the 1th position from the Vector but that does not point to itself anymore. It is removing the #2 thread. Sooner or later you are going to get an exception when the remove happens because it is going to be removing an invalid index.
You need to remove items from the Vector by address and not by position:
tList.remove(this);
That will remove the current thread from the list. You should also just do an add(t) instead of an add(i t) in the start loop:
tList.add(t);
You now don't need the id position passed into your thread at all.
I don't see where you are removing the finished threads from your tList. I see a definition (not that you edited your OP) of a removeFromTList() method but I don't see it used anywhere. In tMonitor you are in a while loop here:
while(tList.size() > 0) {
try {
sleep(10000);
} catch(Exception e) {
e.printStackTrace();
}
}
// you never get to this line
        waitingLock.notifyAll();
But I don't see anything that removes the thread from the list. Maybe when the threads each finish they are supposed to remove themselves?
If tMonitor thread never gets out of that loop then it never calls:
waitingLock.notifyAll();
So the main thread will hang forever in waitUntilFinished();.
synchronized(waitingLock) {
while(!isShutDown()) {
try {
waitingLock.wait();
} catch(Exception e) {
e.printStackTrace();
}
}
Also, you don't want to do a sleep in tMonitor() because you are in a synchronized block. You should be doing a:
waitingLock.wait(10000);
Nothing will ever notify it but it's bad form to hold the lock like that in a sleep.

Categories