I have a component that some where inside it opens a thread to create Session,
I can not go in or change anything inside.
I need to find a way to suspend the work till the inner Thread is finished.
(Cant check if session created and therefor cant create loop to wait while !session)
public class Agenda {
Work work=new Work();
public void go(){
work.start();
}
}
public class Work extends Thread {
#Override
public void run() {
for(int i=0; i<10;++i)
System.out.print("!->!");
System.out.println("\n");
super.run();
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Hello SmartHead!!");
Agenda agenda=new Agenda();
agenda.go();
//synchronized (work) {
synchronized (agenda) {
System.out.println("Finished !!! ");
}
}
}
Related
This question already has answers here:
java.lang.IllegalThreadStateException
(6 answers)
Closed 2 years ago.
I am trying to create a game and have come across a bizarre issue with the way I choose to run my Threads
The way I have it set up is that each pertinent class has a Thread Object, who's run() function runs the code once. Each is called once every frame.
However whenever I try to run the code I get a java.lang.IllegalThreadStateException and I have no clue why.
Here's an adaptation of the problematic code:
public class Test {
public static void main(String[] args) {
while(true) {
ThreadA.run(args);
ThreadB.run(args);
}
}
private static class ThreadA {
private static Thread thread = new Thread() {
#Override
public void run() {
System.out.println("A");
}
};
public static void run(String[] args) {
thread.start();
}
}
private static class ThreadB {
private static Thread thread = new Thread() {
#Override
public void run() {
System.out.println("B");
}
};
public static void run(String[] args) {
thread.start();
}
}
}
The problem is here:
while(true) {
ThreadA.run(args);
ThreadB.run(args);
}
This will loop infinitely. It is never legal to start a thread more than once - even if it has completed. thread.isAlive() won't help you here - if you want to run it again, make a new instance.
You're calling Thread#start over and over. It's throwing IllegalStateException because the threads internal status must be equal to 0 for it to start. Anything other than 0 means it has run, is running, or is disposed of.
As per JavaDoc:
It is never legal to start a thread more than once. In particular, a
thread may not be restarted once it has completed execution.
If you intend to run the threads infinitely, you can do it as
public class Test {
public static void main(String[] args) {
ThreadA.run(args);
ThreadB.run(args);
}
private static class ThreadA {
private static Thread thread = new Thread() {
#Override
public void run() {
while (true) {
System.out.println("A");
}
}
};
public static void run(String[] args) {
thread.start();
}
}
private static class ThreadB {
private static Thread thread = new Thread() {
#Override
public void run() {
while (true) {
System.out.println("B");
}
}
};
public static void run(String[] args) {
thread.start();
}
}
}
I am new to threads in Java and hence have this doubt. I read that a 'synchronized non-static method block' allows only one thread to enter the block (for one instance of non-static block, of-course). However it doesn't seem to work. Am I missing something?
Look at the following code.
class A extends Thread
{
public void run()
{
B.b.add();
}
}
class B
{
static B b=new B();
int i;
public synchronized void add()
{
i++;
}
}
public class Sample
{
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
new A().start();
}
System.out.println(B.b.i);
}
}
One problem here is that your main thread doesn't wait for the other threads to finish before it tries to retrieve the result. Using Thread#join works if you want to wait for a single thread, but here we want to wait for all 10. Modifying the program to use CountDownLatch makes the main thread wait until all the threads it created are finished.
Another problem is that the updated value of i isn't guaranteed to be visible. JVM implementations differ about how aggressively they perform optimizations (like delaying refreshes of cached values, or reordering bytecode) that may make the changes to i not visible to the main thread. Adding a synchronized method on the same lock as the add method to fetch the value of i fixes the visibility issue.
import java.util.concurrent.CountDownLatch;
class A extends Thread {
private CountDownLatch latch;
public A(CountDownLatch latch) {
this.latch = latch;
}
#Override public void run() {
B.b.add();
latch.countDown();
}
}
class B {
static B b=new B();
int i;
public synchronized void add() {
i++;
}
public synchronized int getI() {
return i;
}
}
public class Sample {
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(10);
for(int i=0;i<10;i++) {
new A(latch).start();
}
latch.await();
System.out.println(B.b.getI());
}
}
Where and how to implement addShutdownHook in a class, which have no main method? Can this used to kill all the active sockets initialized by that class?
This Might work for you,
public class AddShutdownHookSample {
public void attachShutDownHook(){
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Inside Add Shutdown Hook");
}
});
System.out.println("Shut Down Hook Attached.");
}
}
And in main Method:
public static void main(String[] args) {
AddShutdownHookSample sample = new AddShutdownHookSample();
sample.attachShutDownHook();
System.out.println("Last instruction of Program....");
System.exit(0);
}
Describe whole thing that you are trying to do and show the very exact point where you are having trouble this would be easier for other to help you.
The following is an example, this may help you
public class RuntimeDemo {
// a class that extends thread that is to be called when program is exiting
static class Message extends Thread {
public void run() {
System.out.println("Bye.");
}
}
public static void main(String[] args) {
try {
// register Message as shutdown hook
Runtime.getRuntime().addShutdownHook(new Message());
// print the state of the program
System.out.println("Program is starting...");
// cause thread to sleep for 3 seconds
System.out.println("Waiting for 3 seconds...");
Thread.sleep(3000);
// print that the program is closing
System.out.println("Program is closing...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Done like this...
static {
Runtime.getRuntime().addShutdownHook ( new Thread() {
public void run() {
server.shutdown();
}
} );
}
Hi I'm using the next code to try to stop a thread, but when I see that Running is false it becomes true again.
public class usoos {
public static void main(String[] args) throws Exception {
start();
Thread.sleep(10000);
end();
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(){
System.out.println("finished.");
start().shutdown();
}
}
And the thread
public class SimpleThreads extends Thread {
volatile boolean running = true;
public SimpleThreads () {
}
public void run() {
while (running){
System.out.println("Running = " + running);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread" + "======Running = " + running);
}
public void shutdown(){
running = false;
System.out.println("End" );
}
}
The problem is that when I try to stop it(I set running to false), it starts again..
Look at this line in the end method:
start().shutdown();
You are not stopping the original instance; you are starting another one, which you then immediately shut down.
There is no connection between your start and end methods—no information, no reference is passed from one to the other. It is obviously impossible to stop the thread you started in the start method.
Your end method should not be static; in fact, you don't even need it, shutdown is already it:
SimpleThreads t = start();
Thread.sleep(10000);
t.shutdown();
Because in the end method you just create a new Thread and kill it, save the thread instance and kill it:
Your code should look something like this:
public class usoos {
public static void main(String[] args) throws Exception {
SimpleThreads id = start();
Thread.sleep(10000);
end(id);
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(SimpleThreads id){
System.out.println("finished.");
id.shutdown();
}
I have a main class which spawns a thread, let's call them MainClass and MyThread.
public class MainClass extends javax.swing.JFrame {
int sharedVariable;
MyThread threadInstance;
public MainClass (){
sharedVariable = 2;
threadInstance = new MyThread(this);
threadInstance.run();
}
public int getSharedVariable(){ return sharedVariable; }
public static void main(String[] args){
//begin main class
}
}
public class MyThread implements Runnable {
MainClass class;
public MyThread(MainClass main_class){
this.main_class= main_class;
}
#Override
public run(){
while(this.main_class is still active){
//grab status of sharedVariable and wait for x amount of time.
}
}
}
The problem is I do not know how to implement the while condition which checks if the MainClass instance is still alive and if it is, it has to use the this.main_class.getSharedVariable() to get the value of sharedVariable, then wait for x amount of time. MainClass has the main method .
I would recommend holding onto the Thread instance and then calling threadInstance.interrupt() right before the main(...) method exits.
Something like:
public static void main(String[] args){
MainClass mainClass = new MainClass();
try {
...
// do main stuff here
...
} finally {
mainClass.threadInstance.interrupt();
}
}
Then in your thread you'd do:
while(!Thread.currentThread().isInterrupted()){
...
}
You'd also want to handle InterruptedException correctly:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// always a good pattern to re-interrupt the thread here
Thread.currentThread().interrupt();
// if we are interrupted quit
return;
}
Btw, it is very bad form to leak the instance of an object during construction to another thread:
new MyThread(this);
See here: Why shouldn't I use Thread.start() in the constructor of my class?
Also, you aren't starting a thread when you call threadInstance.run();. You are just running it in the current thread. You should use threadInstance.start() but not inside of the constructor like that.
You can use CountDownLatch which is very convenient for such tasks as waiting other threads to finish some activity (you can change Thread.sleep(...) argument in main to, say, 12000L and see what happens):
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
class OtherThread extends Thread {
private final CountDownLatch sharedLatch;
OtherThread(CountDownLatch sharedLatch) {
this.sharedLatch = sharedLatch;
}
#Override
public void run() {
boolean wokenByMain = false;
try {
wokenByMain = sharedLatch.await(10000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
return; // or not return, whatever makes more sense in your case
}
System.out.println("heh: " + wokenByMain);
}
}
class SOSample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
OtherThread otherThread = new OtherThread(latch);
otherThread.start();
System.out.println("Scheduled other thread to be started");
Thread.sleep(1000L);
System.out.println("going to release other thread");
latch.countDown();
}
}
public class MainClass extends JFrame implements Runnable {
public static void main(String [] args) {
final Thread t=new Thread(new MainClass() {
public void run(){
//something
});
Thread t2=new Thread(new MyThread() {
public void run() {
while(t.isAlive) {
//something
}
}
});
}
}