Java StackOverflowError when I try to use Multithreading - java

I Wanted to print the 2 statements from the payFees class while the getReceipt class waits for the execution of the payFees class and vice versa with the getReceipt class and admissionCompleted class using Multithreading
It shows the java.lang.StackOverflowError.
But when I try to Initalise all the objects of these classes and call the start() and join(), It works perfectly.
Please Help.
package codes;
class payFees extends Thread
{
public payFees()
{
this.start();
getReceipt g= new getReceipt();
g.start();
}
public void run()
{
try
{
System.out.println("Withdraw Amount");
Thread.sleep(1000);
System.out.println("Fees Paid");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class getReceipt extends Thread
{
payFees p=new payFees();
public void run()
{
try
{
p.join();
System.out.println("Ask for Receipt");
Thread.sleep(1000);
System.out.println("Receipt collected");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class admissionCompleted extends Thread
{
public static void main(String args[])
{
new payFees();
getReceipt g=new getReceipt();
try
{
g.join();
System.out.println("Wait for confirmation");
Thread.sleep(1000);
System.out.println("Successfully completed admission process");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Related

How to get the main thread reference in a child thread which is in another class?

public class JoinMethod2 extends Thread{
static Thread mainthread;
public static void main(String[] args) throws InterruptedException {
mainthread=Thread.currentThread();
JoinMethod th = new JoinMethod();
th.start();
try {
for(int i = 1; i<=5; i++) {
System.out.println("Main Thread "+i);
Thread.sleep(1000);
}
}
catch(Exception e) {
System.out.println(e);
}
}
}
class Test5 extends Thread {
public void run (){
super.mainthread;//THIS IS NOT WORKING
try {
mainthread.join();//THIS IS NOT WORKING
for(int i = 1; i<=5; i++) {
System.out.println("Child Thread "+i);
Thread.sleep(1000);
}
}
catch(Exception e) {
System.out.println(e);
}
}
}
How to get the main thread reference in a child thread which is in another class?
Make the mainthread static field public so it can be accessed from outside of JoinMethod2.
public class JoinMethod2 extends Thread {
// Note: mainthread is now "public"
public static Thread mainthread;
public static void main(String[] args) throws InterruptedException {
mainthread = Thread.currentThread();
JoinMethod th = new JoinMethod();
th.start();
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class Test5 extends Thread {
public void run () {
try {
// Note: Access the now "public" mainthread field
JoinMethod2.mainthread.join();
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread "+i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
For calling the parent class static reference in child class we have to mention the reference along with parent class name(eg.JoinMethod.mainthread.join();). For calling the static methods, variables in another class, always write Parent class name(.) along with methods or variables.

synchronized not work ,still java.util.ConcurrentModificationException

I have the following Java code:
But the synchronized not work well, Help!
java.util.ConcurrentModificationException
java.util.ConcurrentModificationException at
java.util.HashMap$HashIterator.nextNode(HashMap.java:1442) at
java.util.HashMap$KeyIterator.next(HashMap.java:1466) at
java.util.AbstractCollection.toArray(AbstractCollection.java:196) at
Main.m(Main.java:68) at Main.lambda$main$0(Main.java:25) at
java.lang.Thread.run(Thread.java:748)
public class Main {
public static Set<Object> objectSet = new HashSet<>();
public static void main(String[] args) throws Exception {
new Thread(()->{m();}).start();
new Thread(()->{add();}).start();
}
public static void add() {
while (true){
objectSet.add(new Object());
}
}
public static void m(){
while(true){
try {
synchronized (objectSet) {
List a = Arrays.asList(objectSet.toArray(new Object[0]));
System.out.println(a.size());
}
}catch (Exception e){
e.printStackTrace();
}
try {
Thread.sleep(1000);
}catch (Exception e){
}
}
}
}
Can't synchronize (java.util.ConcurrentModificationException)
The writers should also synchronize on the same object
Change the add method as
public static void add() {
while (true) {
synchronized (objectSet) {
objectSet.add(new Object());
}
}
}

Java - Stop thread from a different class

I'm trying to stop a java thread from a different class, but unable to figure out. I have looked into the below links, googled a lot from past 2 days but unable to nail down. May be a simple thing which i need to change but i'm out of options and hence posting it here.
Referred Links
java external threads (outside the class file it's used)
http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html
http://www.java2novice.com/java_thread_examples/
While typing the question, I referred the below links as well..
Stop a thread from outside
Below is my code sample. I'm able to start the WorkerThread from the MainThread and get into the loop. But unable to stop the thread started using the StopThread class.
I've also used the volatile option suggested in the below link.
http://tutorials.jenkov.com/java-concurrency/volatile.html
I feel I'm making a simple mistake, but not able to identify it.
//class WorkerThread
package main;
public class WorkerThread implements Runnable
{
public WorkerThread() {
isRunning = true;
}
public WorkerThread(boolean False) {
isRunning = False;
}
private volatile boolean isRunning;
public synchronized void stopThread() {
isRunning = false;
}
public synchronized boolean IsThreadRunning() {
return isRunning;
}
#Override
public void run()
{
int i = 1;
while(isRunning)
{
System.out.println("Loop " + i);
i++;
try { Thread.sleep(2000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
//class MainThread
package main;
public class MainThread
{
public static Thread t;
public static void main(String[] args)
{
t = new Thread(new WorkerThread());
t.start();
}
}
//class StopThread
package main;
public class StopThread
{
public static void main(String[] args)
{
//What should i write here to stop the thread started by MainThread
MainThread.t.interrupt();
}
}
public class MainThread
{
public static Thread t;
public static void main(String[] args)
{
t = new Thread(new WorkerThread());
t.start();
}
}
public class StopThread
{
public static void main(String[] args)
{
MainThread.t.interrupt();
}
}
It is not safe to call Thread.stop() it is listed as deprecated in JavaDocs
Also this may be just for the sake of this question, but why does your program have two main methods?
You have an opportunity to make use of what you defined volatile variable and gracefully come out of thread like below:
public class MainThread
{
public static WorkerThread workerThread;
public static void main(String[] args)
{
workerThread = new WorkerThread();
Thread t = new Thread(workerThread);
t.start();
}
}
public class StopThread
{
public static void main(String[] args)
{
Main.workerThread.stopThread();
}
}
Note: This solution works but not a perfect solution.
You can write and read value of isRunning variable from a properties file. This way you can have interaction between two different java processes. ThreadWorker just creates file upon initiation & and just makes attempt to read the file after that. StopThread modifies the properties file when triggered which should be picked up by ThreadWorker.
Check below example:
public class ThreadWorker implements Runnable
{
public volatile static boolean isRunning = false;
public ThreadWorker() {
Properties p = new Properties();
p.setProperty("isRunning", "1");
FileOutputStream out;
try {
//Writes all properties in appProperties file
out = new FileOutputStream("appProperties");
p.store(out, "---Thread Status----");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run()
{
int i = 1;
String status = "1";
while("1".equals(status))
{
status = getStatus();
System.out.println("Loop " + i);
i++;
try { Thread.sleep(2000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
public String getStatus() {
FileInputStream in;
Properties p = new Properties();
try {
in = new FileInputStream("appProperties");
p.load(in);
return p.getProperty("isRunning");
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//class StopThread
public class StopThread
{
public static void main(String[] args)
{
Properties p = new Properties();
p.setProperty("isRunning", "0");
FileOutputStream out;
try {
out = new FileOutputStream("appProperties");
p.store(out, "---Thread Status----");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//class StopThread
public class StopThread
{
public static void main(String[] args)
{
Properties p = new Properties();
p.setProperty("isRunning", "0");
FileOutputStream out;
try {
out = new FileOutputStream("appProperties");
p.store(out, "---Thread Status----");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Make thread t a public member of class MainThread, and then just call MainThread.t.interrupt() from StopThread

Retrieve GPS DATA on a JTextArea with 2 different class

I have a a GPS receptor. I create a class to retrieve all the GPS data on my Eclipse Console.
(This is the code of makia42)
public class COM implements Runnable{
static Thread myThread=null;
static BufferedReader br;
static BufferedWriter wr;
static InputStreamReader isr;
static OutputStreamWriter osw;
static java.io.RandomAccessFile port;
public COM(){ /**Constructeur*/
myThread=new Thread(this);
}
public void start(){
try {
port=new java.io.RandomAccessFile("COM3","rwd");
port.writeBytes("\r\n");
port.writeBytes("c,31,0,0,5\r\n");
port.writeBytes("T,1000,1\r\n");
}
catch (Exception e) {
System.out.println("start "+e.toString());
}
myThread.start();
}
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
System.out.println(st);
}
}
public static void main(String[] args) {
COM temp= new COM();
temp.start();
}
}
I have another class which is a frame containing a button and a JTextArea. This class is in communication with my first class COM.
When i click the button, COM is starting and show me the data in my Eclipse Console.
But now, I'd like to show it on my JTextArea.
How can I do it ?
Best regards,
Tofuw
Take a moment to read about this pattern.
Make the Thread a Subject. Before starting register the instance of the class that contains the JTextArea as the Observer with the instance of the Thread. At the run() instead of printing on the console, use the notify(String);
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
System.out.println(st);
}
}
Change to
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
notifyObservers(st); //Pass the data to the observers.
}
}
EDIT:
I suppose you can rewrite the Thread to a simple class. It will render the program unresponsive while it reads, that's why you have a Thread. I suppose you can implement a cleaner way using Future<String>
public class GpsReader {
public class GenericGPSException extends Exception {
public GenericGPSException(String message, Throwable cause) {
super(message, cause);
}
}
public static void main(String[] args) {
// Example of usage
GpsReader gpsReader = new GpsReader();
String messageFromDevice;
try {
// Try read it
messageFromDevice = gpsReader.getCoordinate();
} catch (GenericGPSException e) {
// Error, what does it says?
messageFromDevice = e.getMessage();
}
JTextArea mockArea = new JTextArea();
// Show to user anything that comes to it.
mockArea.setText(messageFromDevice);
}
private boolean isReady;
private RandomAccessFile port;
public GpsReader() {
}
public String getCoordinate() throws GenericGPSException {
if (!isReady) {
try {
port = new RandomAccessFile("COM3", "rwd");
port.writeBytes("\r\n");
port.writeBytes("c,31,0,0,5\r\n");
port.writeBytes("T,1000,1\r\n");
isReady = true;
} catch (FileNotFoundException e) {
throw new GenericGPSException(
"Error at starting communication to Device ", e);
} catch (IOException e) {
throw new GenericGPSException(
"Error at starting communication to Device ", e);
}
}
try {
return port.readLine();
} catch (IOException e) {
throw new GenericGPSException("Error at reading the Device ", e);
}
}
}

How to tell main thread that part of thread job is done

Is it true that notify works only after thread is finished? In code below I can't get notification until I comment while (true). How to tell main thread that part of thread job is done?
public class ThreadMain {
public Thread reader;
private class SerialReader implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(3000);
synchronized(this) {
System.out.println("notifying");
notify();
System.out.println("notifying done");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
ThreadMain() {
reader = new Thread(new SerialReader());
}
public static void main(String [] args) {
ThreadMain d= new ThreadMain();
d.reader.start();
synchronized(d.reader) {
try {
d.reader.wait();
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}
}
You should try to avoid using wait and notify with the newer versions of Java, as they're difficult to get right. Try using something like a BlockingQueue instead
public class ThreadMain {
public final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<>();
private class SerialReader implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(3000);
System.out.println("notifying");
queue.offer(Boolean.TRUE);
System.out.println("notifying done");
} catch (Exception e) {
System.out.println(e);
}
}
}
}
ThreadMain() {
reader = new Thread(new SerialReader());
}
public static void main(String [] args) {
ThreadMain d= new ThreadMain();
d.reader.start();
try {
d.queue.take(); // block until something is put in the queue
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}
If you want to be notified when the Thread t completes, call t.join() in the calling Thread. This will block until t has finished its Runnable.
As user oddparity noted in the comments, you are calling wait() and notify() on different objects. A possible fix for this would be to make your SerialReader extend Thread rather than implement Runnable and then assigning reader to be a new instance of the SerialReader directly. :
public class ThreadMain {
public Thread reader;
private class SerialReader extends Thread {
public void run() {
while (true) {
try {
Thread.sleep(3000);
synchronized(this) {
System.out.println("notifying");
notify();
System.out.println("notifying done");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
ThreadMain() {
reader = new SerialReader();
}
public static void main(String [] args) {
ThreadMain d= new ThreadMain();
d.reader.start();
synchronized(d.reader) {
try {
d.reader.wait();
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}
}
If you want to use Runnable with wait()/notify() you can do it this way :
public class ThreadMain {
public Thread reader;
private class SerialReader implements Runnable {
public void run() {
Thread thisThread = Thread.currentThread();
while (true) {
try {
Thread.sleep(3000);
synchronized (thisThread) {
System.out.println("notifying");
thisThread.notify();
System.out.println("notifying done");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
ThreadMain() {
reader = new Thread(new SerialReader());
}
public static void main(String[] args) {
ThreadMain d = new ThreadMain();
d.reader.start();
synchronized (d.reader) {
try {
d.reader.wait();
System.out.println("got notify");
} catch (Exception e) {
System.out.println(e);
}
}
}
}

Categories

Resources