Printing a statement using threads in Java [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am trying to print a statement in Java using threads, where each thread should print part of the statement. However, following code does not always output statement in correct order.
class NewThread implements Runnable {
String msg;
Thread t;
NewThread(String str) {
t = new Thread(this);
msg = str;
}
public void run() {
PrintMsg(msg);
}
synchronized void PrintMsg(String msg) {
System.out.println(msg);
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception");
}
System.out.println(msg);
notify();
}
}
class ThreadDemo {
public static void main(String args[]) {
NewThread t1, t2, t3;
t1 = new NewThread("Humphry Dumprey");
t2 = new NewThread("went to the hill");
t3 = new NewThread("to fetch a pail of water");
t1.t.start();
t2.t.start();
t3.t.start();
try {
t1.t.join();
t2.t.join();
t3.t.join();
} catch (InterruptedException e) {
System.out.println("Main Thread Interrupted");
}
}
}
I suspect problem with inter-thread communication.

I think your problem is in this method:
synchronized void PrintMsg(String msg) {
System.out.println(msg);
try {
wait();
} catch (InterruptedException e) {
System.out.println("Exception");
}
System.out.println(msg);
notify();
}
The thread that call it are going to call wait() which causes them to wait indefinitely for someone to call notify(). But there are no other calls to notify() so they all will stop there.
Also, because the method is synchronized each thread is also waiting on it's own NewThread instance. I think you meant to have all threads waiting and notifying on the same object?
From comments:
want to wait a thread until it finishes writing a part of statement. It should be like this : Thread 1 prints "Humphry Dumprey" Thread 2 prints "went to the hill" Thread 3 prints "to fetch a pail of water" and these three threads should execute in sequence such that the statement gets printed in right sequence.
I never understand these sorts of questions. The whole point of threads are that the run asynchronously in parallel. If you want them to print 3 things in a row then 1 thread should be used instead.
If you need to do this for some assignment then there a couple different ways you can do it.
Each thread could synchronize on the same AtomicInteger. Thread #1 would do its print if the integer was 1, thread #2 when it is 2, .... You could pass in the order as a value field to the NewThread constructor. After they print they values they increment the integer and notifyAll().
static final AtomicInteger counter = new AtomicInteger(1);
...
synchronized (counter) {
// looping like this is always recommended
while (counter.get() != value) {
counter.wait();
}
System.out.println(...);
counter.incrementAndGet();
counter.notifyAll();
}
You could use 2 CountdownLatch so thread #2 calls countDown1.await(); and thread #3 waits for countDown2.await();. Then after thread #1 prints its message it calls countDown1.countDown() and after thread #2 prints its message it calls countDown2.countDown().

Related

Significance of use of keyword synchronized in the following code

I was reading multi threading in Java from the book Java The Complete Reference by Herbert Schildt. I came across following code [Pg. 252, 7th ed.] that explained the usage of wait() and notify() to suspend and resume threads in modern Java. My question is regarding the significance of the keyword synchronization at two places in following code (in run() method of class NewThread):
// Suspending and resuming a thread the modern way.
class NewThread implements Runnable {
String name;
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
suspendFlag = false;
t.start();
}
// This is the entry point for thread.
public void run() {
try {
for (int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized (this) { //First doubt here
while (suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() { //Second doubt here
suspendFlag = false;
notify();
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
Thread.sleep(1000);
ob1.myresume();
ob2.mysuspend();
Thread.sleep(1000);
ob2.myresume();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
//some code
}
My doubt here: I know about the use of keyword synchronization i.e. allowing only one thread to enter a synchronized method on the same object but here we have two threads running on two different objects. So what is the significance of both synchronization keywords used in above code.
I tried running the above code by removing the synchronized keyword at each place differently and simultaneously. I am getting the same error: java.lang.IllegalMonitorStateException: current thread is not owner different number of times and at different line numbers depending upon if I remove both or only one (and which one) synchronization keyword. I looked for the above error and found an explanation for it here but still couldn't connect the answer to my doubt.
The problem that synchronized solves is, it allows the two threads to have a consistent view of the shared suspendFlag variable.
In some real program, a thread might set other shared variables before setting susependFlag=false. If synchronized was not used, then the waiting thread could wake up, and see suspendFlag==false, but not see the other variables set. Or worse, it could see some of them set, but not others.
Without synchronization, Java does not guarantee that different threads will see variables updated in the same order.
I am getting the same error: java.lang.IllegalMonitorStateException: current thread is not owner.
The Java library is trying to help you by forcing you to use synchronized before it will allow you to use wait() and notify(). The rule is simple: You can only call o.wait() or o.notify() or o.notifyAll() from code that is inside a synchronized(o) block. If you break that rule, then the library throws the exception.
When your code calls o.wait() the wait() call temporarily unlocks the monitor lock so that the other thread will be able to synchronize on o and call o.notify(). The o.wait() call is guaranteed to re-lock o before it returns.

Can we Access Synchronized method and an unsynchronized method of same instance from multiple threads at the same time?

It might seem to be a very naive question but I cannot find any concrete answer anywhere. I tried it even practically but since we cannot predict the behaviour of threads resource allocation in Java, it's really difficult to determine.
I just want to know if I can access a synchronized method and and unsynchronized method of a class at the same time from two different threads of same instance of that class ?
Don't see any problems. Try out this:
public class Main {
public static final SyncNotsynced sn = new SyncNotsynced();
public static void main(String[] args){
Thread t1 = new Thread(sn::synced);
Thread t2 = new Thread(sn::notsynced);
t1.start();
t2.start();
}
public static class SyncNotsynced {
public synchronized void synced(){
System.out.println(Thread.currentThread().getName() + " enter synced");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + " exit synced");
}
public void notsynced(){
System.out.println(Thread.currentThread().getName() + " enter notsynced");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + " exit notsynced");
}
}
}
or take look at the live example :). As you can see enterings of Thread 1 and Thread 2 are both happened before exiting:
Thread-0 enter synced
Thread-1 enter notsynced
Thread-0 exit synced
Thread-1 exit notsynced
For a formal explanation you can read JLS 17, but in short only one thread can enter a synchronized block on the same object monitor.
Btw, I used Thread.sleep because (emphasize mine):
Thread.sleep causes the currently executing thread to sleep
(temporarily cease execution) for the specified duration, subject to
the precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors, and resumption of execution
will depend on scheduling and the availability of processors on which
to execute the thread.

Java thread wait and monitor boolean [duplicate]

I have 2 matrices and I need to multiply them and then print the results of each cell. As soon as one cell is ready I need to print it, but for example I need to print the [0][0] cell before cell [2][0] even if the result of [2][0] is ready first. So I need to print it by order.
So my idea is to make the printer thread wait until the multiplyThread notifies it that the correct cell is ready to be printed and then the printerThread will print the cell and go back to waiting and so on..
So I have this thread that does the multiplication:
public void run()
{
int countNumOfActions = 0; // How many multiplications have we done
int maxActions = randomize(); // Maximum number of actions allowed
for (int i = 0; i < size; i++)
{
result[rowNum][colNum] = result[rowNum][colNum] + row[i] * col[i];
countNumOfActions++;
// Reached the number of allowed actions
if (countNumOfActions >= maxActions)
{
countNumOfActions = 0;
maxActions = randomize();
yield();
}
}
isFinished[rowNum][colNum] = true;
notify();
}
Thread that prints the result of each cell:
public void run()
{
int j = 0; // Columns counter
int i = 0; // Rows counter
System.out.println("The result matrix of the multiplication is:");
while (i < creator.getmThreads().length)
{
synchronized (this)
{
try
{
this.wait();
}
catch (InterruptedException e1)
{
}
}
if (creator.getmThreads()[i][j].getIsFinished()[i][j] == true)
{
if (j < creator.getmThreads()[i].length)
{
System.out.print(creator.getResult()[i][j] + " ");
j++;
}
else
{
System.out.println();
j = 0;
i++;
System.out.print(creator.getResult()[i][j] + " ");
}
}
}
Now it throws me these exceptions:
Exception in thread "Thread-9" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-6" Exception in thread "Thread-4" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-5" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-8" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-7" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-11" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-10" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
Exception in thread "Thread-12" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at multiplyThread.run(multiplyThread.java:49)
line 49 in multiplyThread is the "notify()"..I think I need to use the synchronized differently but I am not sure how.
If anyone can help this code to work I will really appreciate it.
To be able to call notify() you need to synchronize on the same object.
synchronized (someObject) {
someObject.wait();
}
/* different thread / object */
synchronized (someObject) {
someObject.notify();
}
While using the wait and notify or notifyAll methods in Java the following things must be remembered:
Use notifyAll instead of notify if you expect that more than one thread will be waiting for a lock.
The wait and notify methods must be called in a synchronized context. See the link for a more detailed explanation.
Always call the wait() method in a loop because if multiple threads are waiting for a lock and one of them got the lock and reset the condition, then the other threads need to check the condition after they wake up to see whether they need to wait again or can start processing.
Use the same object for calling wait() and notify() method; every object has its own lock so calling wait() on object A and notify() on object B will not make any sense.
Do you need to thread this at all ? I'm wondering how big your matrices are, and whether there's any benefit in having one thread print whilst the other does the multiplication.
Perhaps it would be worth measuring this time before doing the relatively complex threading work ?
If you do need to thread it, I would create 'n' threads to perform the multiplication of the cells (perhaps 'n' is the number of cores available to you), and then use the ExecutorService and Future mechanism to dispatch multiple multiplications simultaneously.
That way you can optimise the work based on the number of cores, and you're using the higher level Java threading tools (which should make life easier). Write the results back into a receiving matrix, and then simply print this once all your Future tasks have completed.
Let's say you have 'black box' application with some class named BlackBoxClass that has method doSomething();.
Further, you have observer or listener named onResponse(String resp) that will be called by BlackBoxClass after unknown time.
The flow is simple:
private String mResponse = null;
...
BlackBoxClass bbc = new BlackBoxClass();
bbc.doSomething();
...
#override
public void onResponse(String resp){
mResponse = resp;
}
Lets say we don't know what is going on with BlackBoxClass and when we should get answer but you don't want to continue your code till you get answer or in other word get onResponse call. Here enters 'Synchronize helper':
public class SyncronizeObj {
public void doWait(long l){
synchronized(this){
try {
this.wait(l);
} catch(InterruptedException e) {
}
}
}
public void doNotify() {
synchronized(this) {
this.notify();
}
}
public void doWait() {
synchronized(this){
try {
this.wait();
} catch(InterruptedException e) {
}
}
}
}
Now we can implement what we want:
public class Demo {
private String mResponse = null;
...
SyncronizeObj sync = new SyncronizeObj();
public void impl(){
BlackBoxClass bbc = new BlackBoxClass();
bbc.doSomething();
if(mResponse == null){
sync.doWait();
}
/** at this momoent you sure that you got response from BlackBoxClass because
onResponse method released your 'wait'. In other cases if you don't want wait too
long (for example wait data from socket) you can use doWait(time)
*/
...
}
#override
public void onResponse(String resp){
mResponse = resp;
sync.doNotify();
}
}
You can only call notify on objects where you own their monitor. So you need something like
synchronized(threadObject)
{
threadObject.notify();
}
notify() needs to be synchronized as well
I'll right simple example show you the right way to use wait and notify in Java.
So I'll create two class named ThreadA & ThreadB. ThreadA will call ThreadB.
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();//<----Create Instance for seconde class
b.start();//<--------------------Launch thread
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();//<-------------WAIT until the finish thread for class B finish
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
}
and for Class ThreadB:
class ThreadB extends Thread{
int total;
#Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();//<----------------Notify the class wich wait until my finish
//and tell that I'm finish
}
}
}
Simple use if you want How to execute threads alternatively :-
public class MyThread {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(() -> {
try {
synchronized (lock) {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + "A");
lock.notify();
lock.wait();
}
}
} catch (Exception e) {}
}, "T1").start();
new Thread(() -> {
try {
synchronized (lock) {
for (int i = 0; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ":" + "B");
lock.notify();
lock.wait();
}
}
} catch (Exception e) {}
}, "T2").start();
}
}
response :-
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
we can call notify to resume the execution of waiting objects as
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
resume this by invoking notify on another object of same class
public synchronized notifyJoy() {
joy = true;
notifyAll();
}
For this particular problem, why not store up your various results in variables and then when the last of your thread is processed you can print in whatever format you want. This is especially useful if you are gonna be using your work history in other projects.
This looks like a situation for producer-consumer pattern. If you’re using java 5 or up, you may consider using blocking queue(java.util.concurrent.BlockingQueue) and leave the thread coordination work to the underlying framework/api implementation.
See the example from
java 5:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html
or java 7 (same example):
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
You have properly guarded your code block when you call wait() method by using synchronized(this).
But you have not taken same precaution when you call notify() method without using guarded block : synchronized(this) or synchronized(someObject)
If you refer to oracle documentation page on Object class, which contains wait() ,notify(), notifyAll() methods, you can see below precaution in all these three methods
This method should only be called by a thread that is the owner of this object's monitor
Many things have been changed in last 7 years and let's have look into other alternatives to synchronized in below SE questions:
Why use a ReentrantLock if one can use synchronized(this)?
Synchronization vs Lock
Avoid synchronized(this) in Java?

Print data after all the threads finished [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to print an array only after 2 threads that I created are finish run method.
How can iI do that?
Take a look at the method Thread#join(). For example:
Thread a = ...;
a.start();
a.join(); // wait until Thread a finishes
Simple. Use Thread.join(). While you are spawning your threads add them into a list and loop through that list and call thread.join(). Once you get out of that loop, all your threads are confirmed to be finished. Then you can have the print statement after that.
Something like this:
import java.lang.*;
public class ThreadDemo implements Runnable {
public void run() {
//some implementation here
}
public static void main(String args[]) throws Exception {
List<Thread> threadList = new ArrayList<Thread>();
Thread t1 = new Thread(new ThreadDemo());
t1.start();
threadList.add(t1);
Thread t2 = new Thread(new ThreadDemo());
t2.start();
threadList.add(t2);
for(Thread t : threadList) {
// waits for this thread to die
t.join();
}
System.out.print("All the threads are completed by now");
}
}
Have you tried anything?
The standard way of having code wait for a thread to finish is to call the join() method on that thread; when that returns, the thread is done. Try looking that up and seeing what you can figure out.
Take a look to this post (How to wait for a set of threads to complete?, How to wait for a number of threads to complete?).
You could submit these jobs to an Executor, each of them will return a Future object. Call the get() method on each of these futures and you'll block until all of them have completed:
String[] myArr = new String[0];
ExecutorService service = Executors.newSingleThreadExecutor();
//Just one task, but repeat with as many as needed.
Future f = service.submit(new Runnable() {
public void run() {
//Executing code
}
});
f.get();
System.out.println(Arrays.toString(myArr)); //Print array.
Thread.join() is the more standard way to wait until a particular thread has completed, but personally in this day and age I prefer this approach - it makes it much easier to say swap out the single threaded executor for a concurrent thread pool (or similar) later should the need arise, and personally I find it neater too. It can also be easily refactored to work with Callables, providing a Future which can directly get the result of the concurrent computation.
Either approach will work, the one which is better for you will depend on your use case.
My opinion is that you should use CountDownLatch.
Before printing you should show this:
CountDownLatch startSignal = new CountDownLatch(2);
// Create your threads and add startSignal as parameters to them
At the end of each thread you shoulf call:
startSignal.countDown();
After that before print you should call:
startSignal.await();
// print...
This will continue after counter reaches zero.

analysing the difference betweeen synchronize and lock [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am a newbie to the world of Threads and I am going through threads to latest util package reentrant lock mechanism, I was going through the basis differences between synchronize mechanism and the newly added lock mechanism , as in the article these were the differences..
Another significant difference between ReentrantLock and synchronized keyword is fairness. synchronized keyword doesn't support fairness. Any thread can acquire lock once released, no preference can be specified, on the other hand you can make ReentrantLock fair by specifying fairness property, while creating instance of ReentrantLock. Fairness property provides lock to longest waiting thread, in case of contention.Please if you could provide a small program which proves this point sp that I can grasp more
main difference between synchronized and ReentrantLock is ability to trying for lock interruptibly, and with timeout. Thread doesn't need to block infinitely, which was the case with synchronized, Please if you could provide a small program which proves this point sp that I can grasp more
One more worth noting difference between ReentrantLock and synchronized keyword in Java is, ability to interrupt Thread while waiting for Lock. In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock. Similarly tryLock() with timeout can be used to timeout if lock is not available in certain time period.Please if you could provide a small program which proves this point sp that I can grasp more
Guys could you please provide a small program which shows all these above three points
I have tried this program , please advise what changes need to be done in it to prove above 3 points..
public class ReentrantLockHowto {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
//Locking using Lock and ReentrantLock
public int getCount() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + " gets Count: " + count);
return count++;
} finally {
lock.unlock();
}
}
//Implicit locking using synchronized keyword
public int getCountTwo() {
return count++;
}
public static void main(String args[]) {
final ThreadTest counter = new ThreadTest();
Thread t1 = new Thread() {
#Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace(); }
}
}
};
Thread t2 = new Thread() {
#Override
public void run() {
while (counter.getCount() < 6) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
};
t1.start();
t2.start();
}
}
Output:
Thread-0 gets Count: 0
Thread-1 gets Count: 1
Thread-1 gets Count: 2
Thread-0 gets Count: 3
Thread-1 gets Count: 4
Thread-0 gets Count: 5
Thread-0 gets Count: 6
Thread-1 gets Count: 7

Categories

Resources