Turn the main into a thread - java

I created a program that runs in a sort of loop, and it stops only if a particular event happens; i forgot to implement the possibility to interrupt the program from "outside", for example typing "halt" in the prompt.
So now i have something like this:
public void main(....) {
instruction1;
instruction2;
while(true) {
if(???)
break;
}
}
And want change it in something like:
main() {
do {
instruction1;
instruction2;
...
...
} while(prompt do not contains 'halt');

I don't think that you want to turn main into a thread, try something like
while(true){
if(inputScanner.hasNext() && inputScanner.next().equals("halt")){
break;
}
/* Do whatever is needed */
}
What happens is that the scanner is checked for input without blocking the loop with the hasNext() method, and then only when it does have data to read in does it read the data in.

Related

Thread is not Stopping/Interrupting

I have this code sample
public static class BlinkMe extends Thread {
int counter = 0;
protected boolean stop = true;
public void run() {
while (stop) {
counter++;
if (counter % 2 == 0) {
jLabel4.setVisible(true);
jLabel7.setVisible(true);
jLabel8.setVisible(true);
counter = 0;
} else {
jLabel4.setVisible(false);
jLabel7.setVisible(false);
jLabel8.setVisible(false);
if (jButton4.isEnabled() == false) {
stop = false;
jLabel4.setVisible(true);
jLabel7.setVisible(true);
jLabel8.setVisible(true);
if (jButton2.isEnabled() == false) {
stop = true;
jButton2.setEnabled(false);
}
}
}
}
}
}
I need to stop this Thread when I press my Stop Button...
Here's the code I'm using for the Button's function but it is not working. ***The Thread is not working at ll*
Here is the Button's function
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
BlinkMe b=new BlinkMe();
b.stop(); //here I have even used b.interrupt(); but doesn't stop the
}
There are many, many things wrong in this code.
you're accessing Swing components from a background thread. That's forbidden. Only the event dispatch thread is allowed to access Swing components
You're trying to stop() a thread, although this method is deprecaed and should never, ever be used, as the documentation explains
Instead of stopping the actual thread, you create a new instance of that thread class, and call stop() on that new instance.
You "blink" without any delay between the blink.
Your thread uses a stop variable, but this variable is never modified anywhere. Even if it was, it's not volatile, so you have a big chance of not seeing the modification, and thus not stopping the thread.
Read the Swing tutorial abount concurrency. And use a Swing Timer, which is designed to do that kind of thing, safely.
You are creating a new thread in actionPerformed and trying to stop the same, which was not started so far. Try calling stop in actual thread.
The initial value of your stop is "true". This means that when the thread starts, the run method executes but will not execute the while block because the condition will result to false right away.
First, you need to change your while loop into like this:
while(!stop) { /* the rest of your code */ }
Next, you need to create a method in your BlinkMe thread that would allow other objects in your program that would make it stop. The method would look something like this:
public void stopBlinking() {
stop = true;
}
Calling the above method will stop the infinite loop in the run method.
I don't think you will see a blinking effect when you run your program. It is because the loop executes very fast. I suggest you put a Thread.sleep(1000) somewhere in the loop so that there is time to reflect the blink effect visually.

check file existance in runtime in java

I want to check whether file exists at required location or not.
I am creating one text file from java e.g. abc.txt. I am going to use this file in some other program let's say a CAD program to generate a drawing. After completion of CAD process, it generates a file with some extension e.g. '.cad'. This drawing generation will take some time.
I am going to use the same '.cad' file in another program let's say an analysis software to analyse the generated drawing.
Now my problem is, I want to check whether the '.cad' file is generated or not. As the generation of .cad file takes time, without this file I can't proceed further i.e. I can't provide this file to next step (i.e. to analysis software).
So, is there any way in java, such that I can check for existence of .cad file for some time (let's say 120 seconds). And if I find the file then only proceed to next step.
I searched about the method file.exists() but it checks only once.
Please give me some hint.
Thank you all in advance!
I guess that you could use daemon for make your task at the background, hope it be helpful friend!
public class DaemonFolder extends Thread {
#SuppressWarnings("deprecation") // stop();
public static void main(String[] args) {
System.out.println("Pulsar enter para finalizar");
DaemonFolder daemonn= new DaemonFolder();
Scanner finalize= new Scanner(System.in);
finalize.nextLine();
daemonn.stop();
finalize.close();
System.out.println("Programa finalizado!");
}
public DaemonFolder() {
setDaemon(true); // Daemon threads in Java are like a service providers for other threads or objects running in the same process as the daemon thread
start();
}
#Override
public void run() {
while (true) {
try {
sleep(5000);
if (new File("anonymous.txt").exists()){
System.out.println("exists");
//DO SOMETHING
} else {
System.out.println("not exists");
}
} catch (Exception e){
e.printStackTrace();
}
}
}
}
You could for example write a for-loop that counts from 0 to 119 and there do the exists check, if it was successful call the next step, if not call Thread.sleep(1000) to wait a second before the next check.
Or you could for example schedule a TimerTask in a Timer to be run each second and in the TimerTask do the exists check and if maximum time is elapsed abort or if check goes well do the next step and abort.
There are plenty ways to do it, these were just two of them.
You need create cycle with your method and Thread.sleep(120000).
Snmth. like this:
while(true) {
if (file.exists()) {
break;
} else {
Thread.sleep(120000);
}
}

Stop executing further code in Java

I have looked in the Javadoc but couldn't find information related to this.
I want the application to stop executing a method if code in that method tells it to do so.
If that sentence was confusing, here's what I want to do in my code:
public void onClick(){
if(condition == true){
stopMethod(); //madeup code
}
string.setText("This string should not change if condition = true");
}
So if the boolean condition is true, the method onClick has to stop executing further code.
This is just an example. There are other ways for me to do what I am trying to accomplish in my application, but if this is possible, it would definitely help.
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).
return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
There are two way to stop current method/process :
Throwing Exception.
returnning the value even if it is void method.
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
You can just use return to end the method's execution
Either return; from the method early, or throw an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
I think just using return; would do the job

Stop current running thread with certain condition, with finally block being called

I have a method which is long and has many inner loops, at some point in the inner loop if a certain condition is met, I want the thread to be terminated but I also want the finally block to be called so clean up also happens. How can I do this?
Call return; when you want to stop. That will leave the loop and run the finally (so long as the loop with the return statement is within the try block).
E.g.
pseudocode:
public void run () {
try {
loop {
loop {
if (condition) return;
}
}
} finally {
// always run
}
}
Remember that "terminating the thread" really just means-- or should mean!-- that the run() method exits. Put the finally outside the loop, as the last thing in the thread's/Runnable's run() method.

Have threads run indefinitely in a java application

I am trying to program a game in which I have a Table class and each person sitting at the table is a separate thread. The game involves the people passing tokens around and then stopping when the party chime sounds.
how do i program the run() method so that once I start the person threads, they do not die and are alive until the end of the game
One solution that I tried was having a while (true) {} loop in the run() method but that increases my CPU utilization to around 60-70 percent. Is there a better method?
While yes, you need a loop (while is only one way, but it is simplest) you also need to put something inside the loop that waits for things to happen and responds to them. You're aiming to have something like this pseudocode:
loop {
event = WaitForEvent();
RespondToEvent(event);
} until done;
OK, that's the view from 40,000 feet (where everything looks like ants!) but it's still the core of what you want. Oh, and you also need something to fire off the first event that starts the game, obviously.
So, the key then becomes the definition of WaitForEvent(). The classic there is to use a queue to hold the events, and to make blocking reads from the queue so that things wait until something else puts an event in the queue. This is really a Concurrency-101 data-structure, but an ArrayBlockingQueue is already defined correctly and so is what I'd use in my first implementation. You'll probably want to hide its use inside a subclass of Thread, perhaps like this:
public abstract class EventHandlingThread<Event> extends Thread {
private ArrayBlockingQueue<Event> queue = new ArrayBlockingQueue<Event>();
private boolean done;
protected abstract void respondToEvent(Event event);
public final void postEvent(Event event) throws InterruptedException {
queue.put(event);
}
protected final void done() {
done = true;
}
public final void run() {
try {
while (!done) {
respondToEvent(queue.take());
}
} catch (InterruptedException e) {
// Maybe log this, maybe not...
} catch (RuntimeException e) {
// Probably should log this!
}
}
}
Subclass that for each of your tasks and you should be able to get going nicely. The postEvent() method is called by other threads to send messages in, and you call done() on yourself when you've decided enough is enough. You should also make sure that you've always got some event that can be sent in which terminates things so that you can quit the gameā€¦
I would look into Locks and Conditions. This way you can write code that waits for a certain condition to happen. This won't take a lot of CPU power and is even much more efficient and better performing than sleeping .
To make a thread run for an infinite time:
final Object obj = new Object();
try {
Thread th = new Thread(new Runnable() {
public void run() {
synchronized(obj) {
try {
System.out.println("Waiting");
obj.wait();
System.out.println("Done waiting");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
});
th.start();
System.out.println("Waiting to join.");
// Dont notify; but wait for joining. This will ensure that main thread is running always.
th.join();
System.out.println("End of the Program");
} catch(Exception ex) {
ex.printStackTrace();
}
You may add Thread.sleep() with appropriate time to minimize useless loop iterations.
Another solution is using synchronization. While threads are not required to do anything, they enter into a sleeping state on a monitor using the wait() method, and then when the turn comes, required thread is woken up by the notify() method.
Actor model seems suitable for this scenario. Each person sitting on the table and the table itself can be modelled as actors and the event of passing the tokens and starting and stopping of the game can be modelled as messages to be passed between the actors.
As a bonus, by modelling the scenario as actors you get rid of explicit manipulation of threads, synchronization and locking.
On JVM I will prefer using Scala for modelling actors. For Java you can use libraries like Kilim. See this post for a comparison of Actor model related libraries in Java.
One Way is to use while loop but keep a check i.e
while(true){
if(condition!=true){
Thread.sleep(time);
}else{
break;
}
}
This way if your condition says game is not over it will keep person thread at sleep and memory consumption will be very low.
You should test for a condition in the while loop:
while (!gameOver)
{
do_intersting_stuff();
}
Heavy CPU load is typical for busy wait. Is your loop actually just checking a flag over and over, like
while (!gameOver)
{
if (actionNeeded)
{
do_something();
}
}
you might change to another notification system to sleep and wake up, as this just burns CPU time for nothing.

Categories