java timer won't work - java

Why won't this work?
I would like it to print every second.
Thanks.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class test2 {
public static void main(String[] args) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
}
});
timer.start();
}
}

Your program terminates before the timer can run even once. When the main method is terminated the program terminates and all threads will also terminate. This includes your timer thread.
Try the following:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class test2 {
public static void main(String[] args) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
}
});
timer.start();
}
while (true) /* no operation */;
}
}

Probably the timer is started in a daemon thread, and immediately after starting it, the main thread finishes.
As soon as there are only daemon threads left, the JVM may/must terminate. So you need to keep the main thread alive. For testing purposes a simple Thread.sleep(10000); should do well.

There's nothing preventing your code from exiting immediately after the call to start. Add Thread.sleep(10000); after timer.start(); and you'll see the message printed.

Because your program will exit soon after main thread is finished, and since timer runs on a separate thread it won't have time to execute. Adding a Thead.Sleep call before main method end would execute your code.

You are using interface libraries (java.awt) to write console applications.
Try this:
public static void main(String[] args) throws Exception {
while(true){
Thread.sleep(1000);
System.out.println("hello");
}
}

Related

How to run method in five seconds duration only

Lets say I have a method called in my android apps
updateArrayList(double data);
How to run the method in 5 seconds and stop after that?
You shuld try Thread.sleep(INT MILLIS); and in try catch block do operation
use the timer class this is the full code
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class ReminderBeep {
Toolkit toolkit;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep(5);
System.out.println("Task scheduled.");
}
}
this code from http://www.java2s.com/Code/Java/Development-Class/UsejavautilTimertoscheduleatasktoexecuteonce5secondshavepassed.htm
You can try this:
try { //you need the try and catch otherwise you get an error
Thread.sleep(5000); //this is the actual waiting
} catch (InterruptedException e) { //this can just be "Exception" it means that if the thread is told to start again, it wont cause an error.
System.out.println("This code was told to start again.");
//whatever you want to do if the code is told to start again during this.
}

Stopping and starting a loop with a button

I am trying to control a while loop in my program to stop and start based on a user input. I have attempted this with a button and the "start" part of it works but then the code goes into an infinite loop which I cant stop without manually terminating it. The following is all my code:
Header Class
package test;
import javax.swing.JFrame;
public class headerClass {
public static void main (String[] args){
frameClass frame = new frameClass();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(150,75);
frame.setVisible(true);
}
}
Frame Class
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class frameClass extends JFrame {
private JButton click;
public frameClass(){
setLayout(new FlowLayout());
click = new JButton("Stop Loop");
add(click);
thehandler handler = new thehandler();
click.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()==click){
looper loop = new looper();
looper.buttonSet = !looper.buttonSet;
}
}
}
}
Looping class
package test;
public class looper {
public static boolean buttonSet;
public looper(){
while (buttonSet==false){
System.out.println("aaa");
}
}
}
How do I fix this and stop if from going into the infinite loop please?
Swing is a single threaded framework, this means that while the loop is running, the Event Dispatching Thread is been blocked and can't process new events, including repaint requests...
You need to start your Looper class inside it's own thread context. This would also mean that your loop flag would need to be declared volatile or you should use an AtomicBoolean so that state can be inspected and modified across thread boundaries
For example...
public class Looper implements Runnable {
private AtomicBoolean keepRunning;
public Looper() {
keepRunning = new AtomicBoolean(true);
}
public void stop() {
keepRunning.set(false);
}
#Override
public void run() {
while (keepRunning.get()) {
System.out.println("aaa");
}
}
}
Then you might be able to use something like...
private class thehandler implements ActionListener {
private Looper looper;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == click) {
if (looper == null) {
looper = new Looper();
Thread t = new Thread(looper);
t.start();
} else {
looper.stop();
looper = null;
}
}
}
}
to run it...
Take a look at Concurrency in Swing and Concurrency in Java for some more details
Also beware, Swing is not thread safe, you should never create or modify the UI from out side the context of the EDT
The problem is you start an infinite loop and try to terminate it in the same thread. That doesn't work because the VM executes one task in a thread after another. It would execute the command to stop the looper directly after the loop is finished but an infinite loop never finishes. So it cannot be stopped like this.
You need to create a second Thread for the looper. This way you can stop it from your main thread.

Why does my java timer stop after seemingly random number of iterations?

I am trying to create a simple java program that will run indefinitely and output a number every second. I believe my code here should do this; however, it stops after the variable i gets to either 2, 3 or 4. Randomly. Most of the time it hits 3. I do not think that the program stopping is based on i at all, but something i'm overlooking perhaps.
All this program needs to do is spit out the second count using a timer. I feel like my code might be a little over complicated so please let me know if i'm making it too hard.
package testing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class driver {
static int delay = 1000; //milliseconds
private Timer timer;
int i = 0;
public driver(){
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println(i);
i++;
}
};
timer = new Timer(delay, taskPerformer);
timer.setInitialDelay(0);
timer.start();
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new driver();
}
});
}
}
Everything is just right in your program, but one.
Your program starts (from main() obviously), which starts the timer, timer method initiates the process of displaying time/number every second, and after that, the main thread dies! resulting in completion of program execution.
So to avoid this you simply can keep main thread busy.
Here's the simplest way :
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
driver d = new driver();
}
});
for(;;); // <-- **Check this out :D**
}

java swing thread problem

In my java swing application am having a Jframe and Jlabel for displaying current time.
here am using a thread for displaying time in jlablel which is added to the frame.my doubt is that when i dispose the jframe what will happen to the thread whether its running or stopped.
If you have NOT marked your thread as daemon by calling yourThread.setDaemon(true), it will keep running even if main thread in your application has finished. Remember you have to call setDaemon before starting the thread.
Refer my answer to some previous question for details.
The correct way in your case, I believe, would be you maintain a 'stop' flag which is watched by your timer thread. Timer thread should exit on reading this flag as 'false'. You can add a WindowListener to your jframe and on the window closed event set the 'stop' flag to true
Heres example code for what I am suggesting :
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class JFrameTest {
public static void main(String[] args) {
final Timer t = new Timer();
t.start();
JFrame jf = new JFrame("GOPI");
jf.setVisible(true);
jf.setSize(100, 100);
jf.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
t.stopTimer();
}
});
System.out.println("JFrameTest.main() DONE");
}
}
class Timer extends Thread {
boolean stop = false;
#Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (stop)
break;
System.out.println("Counting :" + i);
}
System.out.println("Timer exit");
}
public void stopTimer() {
stop = true;
}
}
Your thread will keep running.
You need to either do as suggested by Gopi or you could use System.exit(0) in close operation of your JFrame.
NOTE: I am assuming here that Your application needs to end if this Frame is closed.

Cant get Java Timer working (javax.swing.Timer)

So I'm trying to learn how the javax.swing.Timer works, but I can't get it to do a simple operation. Basically all I'm trying to do is have the system print out "test2" every second, but it seems the actionPerformed method is never called. What am I doing wrong?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class Main
{
public static void main(String[] args)
{
System.out.println("test 1");
final Other o = new Other();
class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("test2");
}
}
//test
System.out.println("test 3");
ActionListener listener = new TimerListener();
//test
System.out.println("test 4");
final int DELAY = 1000;
Timer t = new Timer(DELAY, listener);
//test
System.out.println("test 5");
t.start();
//test
System.out.println("test 6");
}
}
This is the output that the above code produces:
test 1
test 3
test 4
test 5
test 6
Thank you!
The program is exiting before the timer gets a chance to fire. Add a Thread.currentThread().sleep(10000) and you'll see the timer events.
A timer does not force your program to continue running after the main method has finished. Without starting another thread to run or ensuring that the main thread runs for a sufficient amount of time, the timer may never trigger.

Categories