问题
Lately I've been using loops with large numbers to print out Hello World:
int counter = 0;
while(true) {
//loop for ~5 seconds
for(int i = 0; i < 2147483647 ; i++) {
//another loop because it's 2012 and PCs have gotten considerably faster :)
for(int j = 0; j < 2147483647 ; j++){ ... }
}
System.out.println(counter + ". Hello World!");
counter++;
}
I understand that this is a very silly way to do it, but I've never used any timer libraries in Java yet. How would one modify the above to print every say 3 seconds?
回答1:
You can also take a look at Timer and TimerTask classes which you can use to schedule your task to run every n seconds.
You need a class that extends TimerTask and override the public void run() method, which will be executed everytime you pass an instance of that class to timer.schedule() method..
Here's an example, which prints Hello World every 5 seconds: -
class SayHello extends TimerTask {
public void run() {
System.out.println("Hello World!");
}
}
// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);
回答2:
If you want to do a periodic task, use a ScheduledExecutorService. Specifically ScheduledExecutorService.scheduleAtFixedRate
The code:
Runnable helloRunnable = new Runnable() {
public void run() {
System.out.println("Hello world");
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);
回答3:
Try doing this:
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Hello World");
}
}, 0, 5000);
This code will run print to console Hello World every 5000 milliseconds (5 seconds). For more info, read https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html
回答4:
I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer and TimerTask from the same package. See below:
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Hello World");
}
};
Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);
回答5:
Use Thread.sleep(3000) inside for looop
回答6:
public class HelloWorld extends TimerTask{
public void run() {
System.out.println("Hello World");
}
}
public class PrintHelloWorld {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new HelloWorld(), 0, 5000);
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("InterruptedException Exception" + e.getMessage());
}
}
}
}
infinite loop is created ad scheduler task is configured.
回答7:
The easiest way would be to set the main thread to sleep 3000 milliseconds (3 seconds):
for(int i = 0; i< 10; i++) {
try {
//sending the actual Thread of execution to sleep X milliseconds
Thread.sleep(3000);
} catch(InterruptedException ie) {}
System.out.println("Hello world!"):
}
This will stop the thread at least X milliseconds. The thread could be sleeping more time, but that's up to the JVM. The only thing guaranteed is that the thread will sleep at least those milliseconds. Take a look at the Thread#sleep doc:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
回答8:
Use java.util.Timer and Timer#schedule(TimerTask,delay,period) method will help you.
public class RemindTask extends TimerTask {
public void run() {
System.out.println(" Hello World!");
}
public static void main(String[] args){
Timer timer = new Timer();
timer.schedule(new RemindTask(), 3000,3000);
}
}
回答9:
This is the simple way to use thread in java:
for(int i = 0; i< 10; i++) {
try {
//sending the actual Thread of execution to sleep X milliseconds
Thread.sleep(3000);
} catch(Exception e) {
System.out.println("Exception : "+e.getMessage());
}
System.out.println("Hello world!");
}
回答10:
What he said. You can handle the exceptions however you like, but Thread.sleep(miliseconds); is the best route to take.
public static void main(String[] args) throws InterruptedException {
回答11:
Here's another simple way using Runnable interface in Thread Constructor
public class Demo {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 5; i++){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread T1 : "+i);
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread T2 : "+i);
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 5; i++){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread T3 : "+i);
}
}
});
t1.start();
t2.start();
t3.start();
}
}
回答12:
Add Thread.sleep
try {
Thread.sleep(3000);
} catch(InterruptedException ie) {}
回答13:
For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs.
See tutorials for Quartz scheduling.
回答14:
public class TimeDelay{
public static void main(String args[]) {
try {
while (true) {
System.out.println(new String("Hello world"));
Thread.sleep(3 * 1000); // every 3 seconds
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
来源:https://stackoverflow.com/questions/12908412/print-hello-world-every-x-seconds