I am running the program below but for some reason, it dosen't look like I am getting to the run() method. Basically I am trying to spot the behaviour of threads.I am getting the result below :
pqni392fr8dchsdmajglvuqsof
pqni392fr8dchsdmajglvuqsof has wake up
l79uho1tjtot7pcmk4vhh5t8qc
l79uho1tjtot7pcmk4vhh5t8qc has wake up
adfapus6g1fst56daimrudkgji
adfapus6g1fst56daimrudkgji has wake up
iqfo9knc99kcb622g36c77m62
iqfo9knc99kcb622g36c77m62 has wake up
67vdpghqit1a4iv3593451ps0a
67vdpghqit1a4iv3593451ps0a has wake up
As you see I am not getting to the run() method where a thread should sleep.what is the problem?
And another question, could a thread execute the run() from the first run of the program because I noticed that the first line of the output is always from the main().
Thank you.
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
class myThread implements Runnable {
#Override// method run is to be executed by a new thread
public void run() {
System.out.println("I am here");
int timeRandom = new Random().nextInt(50);
try {
String ThrName = Thread.currentThread().getName();
Thread.sleep(timeRandom);
System.out.println("Thread " + ThrName + " sleeping " + timeRandom);
} catch (InterruptedException ex) {
Logger.getLogger(myThread.class.getName()).log(Level.SEVERE, null, ex);
}
// throw new UnsupportedOperationException("Not supported yet.");
}
}
class myClass {
static int nthread = 5;
public static void main(String[] args) {
ExecutorService myService = Executors.newFixedThreadPool(nthread);
while (nthread != 0) {
Thread.currentThread().setName(new BigInteger(130, new SecureRandom()).toString(32));
System.out.println(Thread.currentThread().getName());
myService.submit(Thread.currentThread());
System.out.println(Thread.currentThread().getName() + " has wake up");
//
nthread -= 1;
}
myService.shutdown();
}
}
You never pass an instance of myThread to your ExecutorService, and instead you are performing everything related onto the current thread.
Your code:
Thread.currentThread().setName(new BigInteger(130, new SecureRandom()).toString(32));
System.out.println(Thread.currentThread().getName());
myService.submit(Thread.currentThread());
Code creating expected results:
Thread myThread = new Thread(new myThread());
myThread.setName(new BigInteger(130, new SecureRandom()).toString(32));
System.out.println(myThread.getName());
myService.submit(myThread);
Also, as a side note, Java conventions dictate that class names are declared with capital letters; myClass should be MyClass and myThread should be myThread. That's irrelevant to the runtime issue though.
You are submitting the main thread for your application as a Runnable to the ExecutorService repeatedly. I'm not sure what the defined behavior (if any, could be undefined) of calling run() on the main thread is, but it is certainly not correct. You want to create new myThread objects and submit them to the ExecutorService instead.
Related
I am trying to print out the content of arraylist using 2 threads, my main goal is to make threads read arraylist in a synchronized way and print its content. Eventhough I use synchronized block, I still am getting IllegalMonitorStateException. I know this is a basic question but I can not get it working, pardon me.
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Q1 {
public static Q1 yeni;
public static void main(String[] args) {
// TODO Auto-generated method stub
yeni = new Q1();
}
Q1() {
List<String> list = Collections.synchronizedList(new ArrayList<String>());
list.add("a1");
list.add("b1");
list.add("c1");
list.add("d1");
list.add("e1");
list.add("f1");
ExecutorService executorService = Executors.newFixedThreadPool(10);
synchronized (list) {
myThread thread1 = new myThread(list);
myThread thread2 = new myThread(list);
thread1.start();
thread2.start();
}
}
}
And here is myThread class
import java.util.*;
public class myThread extends Thread {
List<String> liste;
public myThread(List<String> liste) {
this.liste = liste;
}
#Override
public void run() {
try {
synchronized (Q1.yeni) {
System.out.println("Thread number " + this.getName() + " started running.");
for (int i = 0; i < liste.size(); i++) {
System.out.println(liste.get(i));
this.wait(3000);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The reason for the IllegalMonitorStateException is that you are calling wait on an object (this) without holding the monitor for that object. You must either wrap this call with a synchronized (this) block, or call wait on Q1.yeni, which this code already has synchronized.
However, it looks like the use of wait might be mistaken. This method is used to wait on a condition, which is signaled with a call to notify or notifyAll on the same object. Since there is no apparent condition in this code, and no usages of notify or notifyAll, I suspect that what you really want to call is this.sleep(3000), which pauses the thread for three seconds, then resumes it after that duration elapses.
The sleep method does not require ownership of any monitors, and does not release ownership of held monitors, so another thread would not be able to enter the synchronized (Q1.yeni) block while one is currently sleeping. This implies that the first thread to enter that block will run to completion, iterating through the entire list, before the second thread has a chance to begin. It's not totally clear if that's what is intended here.
See the documentation for Object.wait and Thread.sleep for more usage information.
A second problem is that Q1.yeni is accessed by these threads before it is necessarily initialized, because the threads are started in the Q1 constructor, and the statement yeni = new Q1(); only assigns yeni after the constructor completes. In this case, it might be better for the threads to use synchronized (liste) instead.
Other than that, having synchronized (list) in the Q1 constructor does not accomplish much, since the main thread does not access or manipulate the contents of list in that section. The only practical effect is that the threads it starts will block when they reach the first call to liste.size() until the main thread exits the synchronized (list) (immediately after starting the two threads). This has the potential to slightly slow down the first thread that runs, but has no effect on the thread-safety or correctness of the program.
I would also recommend reviewing "How to Handle InterruptedException in Java". In this case, I would recommend restoring the interruption status in the exception handler.
Put together, here is a revised example of this code (including other minor changes to remove unused code and boilerplate comments, improve formatting, and ensure consistency with Java naming conventions):
Q1.java:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Q1 {
private static Q1 yeni;
public static void main(String[] args) {
yeni = new Q1();
}
Q1() {
List<String> list = Collections.synchronizedList(new ArrayList<>());
list.add("a1");
list.add("b1");
list.add("c1");
list.add("d1");
list.add("e1");
list.add("f1");
MyThread thread1 = new MyThread(list);
MyThread thread2 = new MyThread(list);
thread1.start();
thread2.start();
}
}
MyThread.java:
import java.util.*;
public class MyThread extends Thread {
private final List<String> liste;
public MyThread(List<String> liste) {
this.liste = liste;
}
#Override
public void run() {
try {
synchronized (liste) {
System.out.println("Thread number " + this.getName() + " started running.");
for (int i = 0; i < liste.size(); i++) {
System.out.println(liste.get(i));
sleep(3000);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
interrupt();
}
}
}
Output:
Thread number Thread-0 started running.
a1
b1
c1
d1
e1
f1
Thread number Thread-1 started running.
a1
b1
c1
d1
e1
f1
This question already has answers here:
Java wait and notifyAll: IllegalMonitorStateException
(1 answer)
Java Wait and Notify: IllegalMonitorStateException
(2 answers)
Closed 7 years ago.
I need some help to understand where my program is going wrong, I have a very simple program to learn about multithreading but every time I run the following code it gives me an IllegalStateMonitorException. I don't know what's causing this although I suspect it may be my synchronized block, Thanks.
Main Method class:
public class Lab8 {
public static void main(String [] args) {
Thread1 thread1 = new Thread1();
thread1.start();
}
}
Thread 1:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Thread1 extends Thread {
public DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
public Thread1() {
super("Thread1");
}
public void run() {
Thread2 thread2 = new Thread2();
System.out.println("==Start: " + dateFormat.format(new Date()) + "==\n");
synchronized(thread2) {
try {
this.wait();
} catch (InterruptedException e) {
System.err.println(e.toString());
}
(new Thread(thread2)).start();
}
System.out.println("==End: " + dateFormat.format(new Date()) + "==\n");
}
}
Thread 2:
public class Thread2 implements Runnable {
#Override
public void run() {
synchronized(this) {
for(int i = 1; i <= 100; i++) {
System.out.print(i + " ");
if(i % 10 == 0) {
System.out.print("\n");
}
}
notify();
}
}
}
You should understand, that the synchronized construct and the wait/notify mechanism are tied to an object instance. In your code, you are using
synchronized(thread2) {
…
this.wait();
so the object of your synchronized statement and the one, you are calling wait on, are different. That causes the IllegalStateMonitorException. Note that waiting on the Thread1 instance while the other thread is calling notify() on its own Thread2 instance will not work as notify will wake up only threads waiting on the same instance.
Besides that, you should never synchronize on thread instances anyway. The reason is that the Thread implementation will synchronize on its own instance as well, so this might interfere. Further, you should not subclass Thread like you did with your Thread1 class but rather use composition like you did with your Thread2 class.
I am very new to multithreading, was trying a scenario in which a home has a mother(as producer),son,daughter and husband[As consumer] thread.I am trying to understand how wait and notify method can help here.
My classes are as below.
MotherAsProducer
package com.test.All.Threads;
public enum MotherAsProducer {
INSTANCE;
/*
*
*
* son Give request to prepare chapati to mother
* mother accepts it and start preparing , son/husband/daughter should wait by that time.
* mother notifies son/daughtor/husband that chapati is ready start consuming
* */
public synchronized void takeOrderAndMakeChapati(){
try {
System.out.println("Request got from "+Thread.currentThread().getName());
getStatusOfChapati();
wait();
System.out.println(Thread.currentThread().getName()+" ate chapati");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//lock re-entrance
public synchronized void getStatusOfChapati(){
try {
Thread.sleep(1200);
System.out.println("Chapati is prepared for "+Thread.currentThread().getName());
notifyAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static MotherAsProducer getMotherInstance(){
return MotherAsProducer.INSTANCE;
}
}
SonAsConsumer class
package com.test.All.Threads;
public class SonAsConsumer implements Runnable{
public void run(){
MotherAsProducer.getMotherInstance().takeOrderAndMakeChapati();
}
}
DaughterAsConsumer class
package com.test.All.Threads;
public class DaughterAsConsumer implements Runnable {
public void run(){
MotherAsProducer.getMotherInstance().takeOrderAndMakeChapati();
}
}
HusbandAsConsumer class
package com.test.All.Threads;
public class HusbandAsConsumer implements Runnable {
public void run(){
MotherAsProducer.getMotherInstance().takeOrderAndMakeChapati();
}
}
Home class
package com.test.All.Threads;
public class Home {
public static void main(String args[]){
SonAsConsumer sac = new SonAsConsumer();
DaughterAsConsumer dac = new DaughterAsConsumer();
HusbandAsConsumer hac = new HusbandAsConsumer();
Thread tsac = new Thread(sac);
tsac.setName("Son");
Thread tdac = new Thread(dac);
tdac.setName("Daughter");
Thread thac = new Thread(hac);
thac.setName("Husband");
tsac.start();
tdac.start();
thac.start();
}
}
My output is different, every time as expected by nature of thread but one of the individual either husband, daughtor or son is not getting complete.
one instance of my output is as below.
Order she got from Daughter
Chapati is prepared for Daughter
Order she got from Son
Chapati is prepared for Son
Order she got from Husband
Chapati is prepared for Husband
Son ate chapati
Daughter ate chapati
My understanding here is when son,daughter and husband will start executing one of them will hit the synchronized method and execute wait() and will hold the lock , from that synchronized method again another synchronized method is called which will contain notify and the lock will be released and another thread will try to get the lock from the blocked pool and will execute in the same manner . here two threads are behaving as expected but the last one is not.
Kindly help here.
Briefly looking, it looks like the last thread to get to the wait will never get notified. Sequencing your calls you have each thread getting a lock, notifying all waiting threads, and then waiting. So, the last thread that hits the wait will never have anyone to notify them that they need to exit.
That is, if Thread A gets the lock initially, then it will do a println and a sleep then a println, then notify all waiting threads (there are none), and then become a waiting thread.
Then, lets say Thread B gets the lock. It will do a println and a sleep, then it will notify all (which will "notify" Thread A), then it will wait.
Now, either Thread C or Thread A will get the lock. If Thread A gets it, it will simply fall through and complete with the "ate" message. Then, Thread C can get the lock and it will eventually notify, waking B which can eat once C "waits". Now, there is no thread left to notify so that C will complete.
This make sense? Did I misread anything?
To verify what I'm suggesting is wrong, simply add in more threads. You should always have the last one that prints "Chapati is prepared for ..." will never eat it.
Fundamentally, I think the confusion is that "Mother" is not actually doing any work. What you probably wanted is to have "Mother" be a thread that has its own work log. So, when one of the other threads gives her work, you set a variable then notify mother and wait as the sibling. The mother will then wake up and do the work and notify the current thread waiting.
See what I mean? Metaphorically, you have 4 people in this program. But, you only have 3 threads.
Change the method in the enum class MotherAsProducer as follows: The unnecessary wait() method caused the issue. Since the method is synchronized, all other threads will be blocked before entering into the method until getting a notification from lock holding thread.
public synchronized void takeOrderAndMakeChapati() {
System.out.println("Request got from " + Thread.currentThread().getName());
getStatusOfChapati();
// wait(); - THIS WAIT IS CAUSING THE PROBLEM
System.out.println(Thread.currentThread().getName() + " ate chapati");
}
Remove wait and notifyAll calls from both takeOrderAndMakeChapati and getStatusOfChapati. You will get the expected result.
As precisely mentioned by Josh, one of the threads (last one) is still waiting for some external notification, and there is nobody to notify. You code is still running in the background. Just call wait(5000) and you can see it happening.
Both methods takeOrderAndMakeChapati and getStatusOfChapati are synchronized, therefore synchronization is not the issue.
Generally threads wait for some external dependency or condition, where some other thread(s) notifies the waiting one, when that condition is fulfilled.
I also tried to understand wait and notify when I started with multithreading. But as soon as I learned to use a Semaphore, I never looked back. Hopefully, the example below will give you some insight into the benefits of using a Semaphore. There is also a lot more useful stuff in the java.util.concurrent package that can be of great help.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class EatChapati {
static int CHAPATI_PREPARE_TIME_MS = 100;
static long RUN_TIME_MS = 2000;
static long SHUTDOWN_TIME_MS = 500;
static int CHAPATI_CONSUMERS = 5;
static volatile boolean stop;
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < CHAPATI_CONSUMERS; i++) {
executor.execute(new ChapatiConsumer(i + 1));
}
try { Thread.sleep(RUN_TIME_MS); } catch (Exception ignored) {}
stop = true;
executor.shutdownNow();
try { executor.awaitTermination(SHUTDOWN_TIME_MS, TimeUnit.MILLISECONDS); } catch (Exception ignored) {}
}
// 1 producer making chapati's
// 'true' for a fair semaphore: longest waiting consumer gets served
static Semaphore chapatiTurn = new Semaphore(1, true);
static AtomicInteger chapatiCount = new AtomicInteger();
static int getChapati(int consumerNumber) {
int chapatiNumber = 0;
boolean haveTurn = false;
try {
chapatiTurn.acquire();
// start of 'synchronized' block
haveTurn = true;
Thread.sleep(CHAPATI_PREPARE_TIME_MS);
chapatiNumber = chapatiCount.incrementAndGet();
System.out.println("Chapati " + chapatiNumber + " prepared for consumer " + consumerNumber);
} catch (Exception e) {
// Triggered by executor.shutdownNow
stop = true;
} finally {
if (haveTurn) {
chapatiTurn.release();
// end of 'synchronized' block
}
}
return chapatiNumber;
}
static class ChapatiConsumer implements Runnable {
int number;
ChapatiConsumer(int number) {
this.number = number;
}
public void run() {
int chapatisConsumed = 0;
while (!stop) {
if (getChapati(number) > 0) {
chapatisConsumed++;
}
}
System.out.println("Consumer " + number + " stopped after consuming " + chapatisConsumed + " chapatis.");
}
}
}
I've created a class called Thread that implements Runnable but I cannot invoke the start() or sleep() methods for some reason. Any time I attempt to do so, I get errors saying that these methods are undefined for the class and suggests that I create them. So I created a new project and copied a sample code to see if there was something wrong with my own code and I received the same errors. Here's the sample code:
class Thread implements Runnable {
private int a;
public Thread (int a) {
this.a = a;
}
public void run() {
for (int i = 1; i <= a; ++i) {
System.out.println(Thread.currentThread().getName() + " is " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
and this is my own code:
public class Thread extends PID implements Runnable {
public Thread() {}; // Empty constructor for thread object
public void run() {
Random gen = new Random(); // Generates random values
int sleepTime; // Sleep time
sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
try {
Thread.sleep();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The thread has been terminated");
}
}
To fix your current error, simply rename your Thread class to MyThread (or whatever), because your Thread class is hiding the java.lang.Thread class.
If you want to stick to Thread, you'll have to use the fully qualified name for java.lang.Thread like this:
try{
java.lang.Thread.sleep(1000);
// ...
Mistakes
Change class name from Thread to MyThread.
run() is called when you invoke start(). Invoke start() using class object.
Thread.sleep(); needs an argument say, sleepTime
Here is the code of what I think you want to do. Tested on Eclipse Juno JDK 1.7
import java.util.Random;
class NewThread implements Runnable {
public NewThread () {
}
public void run() {
Random gen = new Random(); // Generates random values
int sleepTime; // Sleep time
sleepTime = gen.nextInt(60 - 1) + 1; // Generates random sleep time between 1 and 60 seconds
try {
Thread.sleep(sleepTime);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The thread has been terminated");
}
}
class MyThread {
public static void main(String[] args) {
NewThread t = new NewThread();
Thread t1 = new Thread(t);
t1.start();
}
}
Output
The thread has been terminated
Interface Runnable do not have methods start() and sleep(), so be carefull with it. Interface Runnable only have run() method, and Java API recommends " the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods."
See Java API's Runnable documentation here: http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html
In every other cases, your class should extned class Thread.
I am trying to write a basic program using threads. Assuming I have two threads, t1 and t2 and lock x. Assuming lock x is assigned to t1. When would be a situation where t2 would be unable to process due to lock x being assigned to t1? I am trying to create a simple example to demonstrate how locks/threads work.
I appreciate any assistance in this matter.
This is what I got so far:
Class Skywalker:
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Skywalker{
public static void main(String args[]){
Thread t1 = new Thread("station 1");
Thread t2 = new Thread("station 2");
t1.start();
t2.start();
}
}
Class Darth:
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Darth implements Runnable{
String stationName;
Lock x = new ReentrantLock();
Random r = new Random();
public Darth(String name){
stationName = name;
}
public void run(){
try{
x.lock();
System.out.println(stationName + "is working");
sleep(randomTime);
x.unlock();
} catch(Exception e) {
}
}
}
You should put the lock in one single class to protect a "resource access", for instance:
class SharedResource {
private static Lock lock = new ReentrantLock();
public static void consumeResource(){
try{
lock.lock();
//just one thread a time here
int i = 10;
//mock consuming shared resource:
while(i>0){
i--;
System.out.println(Thread.currentThread().getName() + " is in");
Thread.sleep(1000);
}
}finally{
lock.unlock();
}
}
}
Now just one thread a time will be able to access the lines of code in consumeResource method that are within the lock/unlock statements. It is easy to show that invoking consumeResource from Darth run method.