Set time between two if loops in java - java

Hi i want to set the time interval for few seconds between two if conditions. In my coding first "if" condition executes, control will stop 3 seconds after that only second "if" condition will execute.I dont want to use thread thread concept. I want some other option in java like "Timer" class etc.I tried many times but cant find solution . Please give solution for that
Thanks in advance
Here my code:
package com.example;
public class TimeBetween {
public static void main(String[] args) {
int a=5;
int b=3;
int c;
if(a!=0&&b!=0) {
c=a+b;
System.out.println("Addition:"+c);
}
if(a!=0&&b!=0) {
c=a-b;
System.out.println("Subtraction:"+c);
}
}
}

1) if is not loop, it is like conditional block
2) You may use sleep(milliseconds); after first if() { ...} block.
From oracle documentation:
Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

The most elegant solutions are either Thread.sleep or you could simulate sleep with:
Object o = new Object();
synchronized(o) {
o.wait(3000);
}
If you want to use timer you could do something like this:
But beware that the timer starts a thread in the background.
import java.util.Timer;
import java.util.TimerTask;
public class TimeBetween {
/**
* #param args
*/
public static void main(String[] args) {
final int a = 5;
final int b = 3;
Timer t = new Timer(true);
t.schedule(new TimerTask() {
#Override
public void run() {
int c;
if (a != 0 && b != 0) {
c = a + b;
System.out.println("Addition:" + c);
}
}
}, 0);
t.schedule(new TimerTask() {
#Override
public void run() {
int c;
if (a != 0 && b != 0) {
c = a - b;
System.out.println("Subtraction:" + c);
}
}
}, 3000);
}
}

Related

how to print one character at a time on one line using a METHOD

So I'm well aware that I can delay lines using the following code
long time=100L;
listLine[1] = "You are on a war-torn Plateau";
for ( int i= 0; i < listLine[1].length(); i++) {
// for loop delays individual String characters
System.out.print(listLine[1].charAt(i));
Thread.sleep(time); //time is in milliseconds
}
System.out.println(""); // this is the space in between lines
;
However using this repeatedly in code is redundant and makes it hard to read my code. Is there a way to implement a function/method so that the code instead looks akin to the following.
public static void delay() {
// your solution to my problem goes here
System.out.print(listLine[0].delay();
Thank you in advance :)
It looks like you're trying to create a delayed typing effect based on the first code snippet. The code there should be fine, all you need to do is migrate that code into a method so you can repeatedly create that delayed effect.
public void delay(String s, long delay) {
for ( int i= 0; i < s.length(); i++) {
// for loop delays individual String characters
System.out.print(s.charAt(i));
Thread.sleep(delay); //time is in milliseconds
}
System.out.println(""); // this is the space in between lines
}
Followed by a method call such as
delay("You are on a war-torn Plateau", 100L);
You can first convert a string to character array and then print this using code
public static void main(String[] args){
String sample = "Hello World";
printCharactersWithDelays(sample, TimeUnit.MILLISECONDS, 400);
}
public static void printCharactersWithDelays(String sample, TimeUnit unit, long delay){
List<Character> chars = sample.chars().mapToObj(e->(char)e).collect(Collectors.toList());
chars.forEach(character -> {
System.out.println(character);
try {
unit.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
Here is your answer :
package stack;
import java.util.Timer;
import java.util.TimerTask;
public class Scheduling {
String string = "You are on a war-torn Plateau";
Timer timer;
int index = 0;
public Scheduling() {
timer = new Timer();
//this method schedule the task repeatedly with delay of 1sec until the timer is not cancel
timer.schedule(new Delay(), 0, 1000);
}
public class Delay extends TimerTask {
#Override
public void run() {
if (index == string.length()) {
timer.cancel();
} else {
System.out.println(string.charAt(index));
index++;
}
}
}
public static void main(String[] args) {
new Scheduling();
}
}
In above answer I use java.util.Timer class for timing and TimerTask class is used to do task which we want to do with delay.

Thread cannot stop

why my thread can't be stopped???
class Threadz {
class runP implements Runnable {
int num;
private volatile boolean exit = false;
Thread t;
public runP() {
t = new Thread(this, "T1");
t.start();
}
#Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
num++;
try {
t.sleep(200);
} catch(InterruptedException e) {}
}
}
public void stop() {
exit = true;
}
}
public static void main(String[] a) {
runP rp = new Threadz().new runP();
if(rp.num == 1) {rp.stop();}
}
}
if i use rp.num == 0, the thread can be stopped immediately. But, why when i changed the rp.num == x (x is any number greater than 0) the thread cannot stop? please help me solve this thing... thanks for any helps.
Because this code is not executed in the run() method of the thread :
runP rp = new Threadz().new runP();
if (rp.num == 1) {
rp.stop();
}
It works with 0 as the default value of int is 0.
But it is not necessarily true in all executions of the application as the thread of runP could run and incrementnum before the check : if (rp.num == 0)
Move the stop condition in the run method of the runP thread :
#Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
num++;
try {
t.sleep(200);
} catch(InterruptedException e) {}
if (rp.num == 1) {
exit = true;
}
}
}
I'm sure if you run the program many many times, It'll be a case when the program actually stops.
The reason is at the time you run the program there is much more chance of executing
if(rp.num == 1) {rp.stop();}
before num++ in your run() method changes value.
However by chance you may come across a case that the loop in your run method gets executed before that if statement in your main method.
one way to make sure this happens is to continuously checking for the condition:
e.g.
public static void main(String[] a) {
runP rp = new Threadz().new runP();
while(true){
if(rp.num == 1) {
rp.stop();
break;
}
}
}
Statement below is getting executed before the thread starts executing the run method.
if(rp.num == 1) {rp.stop();}
Add Thread.sleep before the above statement, it works fine as it will execute this statement after starting the loop.
public static void main(String[] a) {
runP rp = new Threadz().new runP();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(rp.num > 1) {rp.stop();}
}
I have made it >1 to test.
Checking rp.num == 1 would have to happen exactly at a point where rp.num is exactly one, which is rather unlikely.
In your main method, you start a thread which increments num every 200 ms. Afterwards, you check if num == 1, but when exactly this code is executed depends on a lot of factors you cannot really control (scheduling of the OS, etc...). This might be after 10 ms (where the value would be 1), but could also be after 300 ms (when the value is already 2). Also when the thread is exactly started is unsure. Therefore it is also possible that your thread only starts after the test. You can easily test this by replacing the check if(rp.num == 1) {rp.stop()}; with a simple print statement System.out.println(rp.num). If you additionally wait for some time before printing, you might get a better feeling of what I am talking about.
Supposing you would like to stop a runnable from outside, I suggest to use something like the Observer pattern:
class MyRunnable implements Runnable {
private final MyListener l;
private volatile boolean exit;
int num;
public MyRunnable(MyListener l) {
this.l = l;
exit = false;
}
#Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
l.check(num++);
try {
t.sleep(200);
} catch(InterruptedException e) {}
}
}
public void stop() {
exit = true;
}
}
class MyListener {
private final threshold;
public MyListener(int x) {
this.threshold = x;
}
public void check(MyRunnable r, int num) {
if (num >= threshold)
r.stop();
}
}
and your main method would look something like
public static void main(String[] args) {
MyListener l = new MyListener(1);
Runnable r = new MyRunnable(l);
new Thread(r).start();
}

How do you use ticks in bukkit?

I understand ticks, 20 ticks to a second etc. but i don't get the syntax. Can someone explain to me the steps of making something with ticks? I have a fireball move here as an example of something i need ticks for; after each time it does the effect, i need it to wait like, 2 ticks. I've looked at other examples but i really don't understand the syntax
#EventHandler
public void onPlayerInteractBlockFireBall(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (player.getItemInHand().getType() == Material.MAGMA_CREAM){
List<Block> targets = player.getLineOfSight((Set)null, 30);
for (Block targetblock : targets){
Location target = targetblock.getLocation();
player.getWorld().playEffect(target, Effect.MOBSPAWNER_FLAMES,5);
}
}
}
I need to know how to add a delay to a loop, timing is really important in this plugin i'm trying to make and i just need to know the syntax.
Anyone help?
To make a timer, you can use
Bukkit.getServer().getScheduler().runTaskLater(plugin, new Runnable(){
public void run(){
//code
}
},ticksToWait);//run code in run() after ticksToWait ticks
So, if you wanted to wait 2 ticks before running the function shootFireball(), for example, you could use
Bukkit.getServer().getScheduler().runTaskLater(plugin, new Runnable(){
public void run(){
shootFireball();
}
},2L);//run code in run() after 2 ticks
plugin will be the instance of your Main class (the one that extends JavaPlugin). So, for example, your onEnable and onDisable functions in your Main class could look like this:
public static Main that; //in your case "plugin" would be "Main.that"
#Override
public void onEnable(){
that = this; //Main.that is now equal to this class
}
#Override
public void onDisable(){
that = null; //Set to null to prevent memory leaks
}
So, your code could look something like this:
#EventHandler
public void onPlayerInteractBlockFireBall(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (player.getItemInHand().getType() == Material.MAGMA_CREAM){
List<Block> targets = player.getLineOfSight((Set)null, 30);
for (int i = 0; i < targets.size(); i++){
//call the spawnFlames with "i * 2" ticks, because
//every time "i" is incremented, there is a new target block
//which means we should wait 2 more ticks than the previous
//iteration before running the task
spawnFlames(player, targets.get(i), i * 2);
}
}
}
public void spawnFlames(final Player player, final Block target, final long ticks){
Bukkit.getServer().getScheduler().runTaskLater(Main.that, new Runnable(){
public void run(){
Location target = targetblock.getLocation();
player.getWorld().playEffect(target, Effect.MOBSPAWNER_FLAMES,5);
}
},ticks);
//run code in run() after "ticks" ticks
//"ticks" will be equal to "i * 2" from
//the onPlayerInteractBlockFireBall() method
}
You will start using Scheduler Programming.
Look carefully at this part of the tutorial.
You need a repeating task for this purpose:
First, create a class that extends BukkitRunnable.
Then override the Runnable.run() method: it will be called once per iteration.
Now start the task with BukkitRunnable.runTaskTimer(Plugin, long, long).
You can stop it at any time using BukkitRunnable.cancel().
You could implement the feature like this:
List<Block> blocks; // The target blocks
BukkitRunnable task = new MagmaEffect(blocks);
Plugin main; // The unique instance of the main class
task.runTaskTimer(main, 0L, 2L);
public class MagmaEffect extends BukkitRunnable {
private List<Block> blocks;
public MagmaEffect(List<Block> blocks) {
this.blocks = blocks;
}
private int index;
#Override
public void run() {
Block block = blocks.get(index);
block.getWorld().playEffect(block.getLocation(), Effect.MOBSPAWNER_FLAMES, 5);
index++;
if (index == blocks.size()) {
cancel();
}
}
}

Is there a code to check if a timer is running?

I have a game where I am scheduling a timer. I have this CoresManager file:
package com.rs.cores;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public final class CoresManager {
protected static volatile boolean shutdown;
public static WorldThread worldThread;
public static ExecutorService serverWorkerChannelExecutor;
public static ExecutorService serverBossChannelExecutor;
public static Timer fastExecutor;
public static ScheduledExecutorService slowExecutor;
public static int serverWorkersCount;
public static void init() {
worldThread = new WorldThread();
int availableProcessors = Runtime.getRuntime().availableProcessors();
serverWorkersCount = availableProcessors >= 6 ? availableProcessors - (availableProcessors >= 12 ? 7 : 5) : 1;
serverWorkerChannelExecutor = availableProcessors >= 6 ? Executors
.newFixedThreadPool(availableProcessors - (availableProcessors >= 12 ? 7 : 5),
new DecoderThreadFactory()) : Executors.newSingleThreadExecutor(new DecoderThreadFactory());
serverBossChannelExecutor = Executors
.newSingleThreadExecutor(new DecoderThreadFactory());
fastExecutor = new Timer("Fast Executor");
slowExecutor = availableProcessors >= 6 ? Executors.newScheduledThreadPool(availableProcessors >= 12 ? 4 : 2,
new SlowThreadFactory()) : Executors
.newSingleThreadScheduledExecutor(new SlowThreadFactory());
worldThread.start();
}
public static void shutdown() {
serverWorkerChannelExecutor.shutdown();
serverBossChannelExecutor.shutdown();
fastExecutor.cancel();
slowExecutor.shutdown();
shutdown = true;
}
private CoresManager() {
}
}
I am using this inside the game:
private void startTimer() {
CoresManager.fastExecutor.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (timer == 0 || timer < 1) {
player.sm("Your timer has ended! The NPCs will no longer spawn.");
timer = 0;
this.cancel();
exitInstance();
return;
}
timer--;
timerchecker = true;
seconds = timer % 60;
player.setTimer(timer);
minutes = TimeUnit.SECONDS.toMinutes(timer);
}
}, 0, 1000);
}
The CoresManager Timer stops running if the player logs out AND the server gets rebooted. To make it run again, I added a code to make it do startTimer() again once you log back in. However, since the timer still runs if the server didn't log out, the timer starts running twice. The Timer starts getting subtracted by 2, or more, depending on how many times you log out and in. I figure that it would fix if there was a code to determine if the timer is already running. Is there a way to do this? Please help!
I don't see anything in the documentation that provides for checking the status on a TimerTask object (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TimerTask.html) so one option would be to extend TimerTask and create your own class. Instead of using an anonymous TimerTask, you could create something along the lines of:
public class CoresTimerTask extends TimerTask {
private boolean hasStarted = false;
#Overrides
public void run() {
this.hasStarted = true;
//rest of run logic here...
}
public boolean hasRunStarted() {
return this.hasStarted;
}
}
and just maintain a reference to this CoresTimerTask object, which you then pass into startTimer(). You can then later check this object via hasRunStarted.
public long scheduledExecutionTime()
Returns the scheduled execution time of the most recent actual execution of this task. (If this method is invoked while task execution is in progress, the return value is the scheduled execution time of the ongoing task The return value is undefined if the task has yet to commence its first execution.
This method is typically not used in conjunction with fixed-delay execution repeating tasks, as their scheduled execution times are allowed to drift over time, and so are not terribly significant.
first thing periodically running tasks need set/reset state flag
second (when i look at examples) it is better to seal this type of class
but if someone insist to have such methods
public abstract class NonInterruptableTask extends TimerTask {
protected boolean isDone = false;
public boolean isDone() {return isDone;}
protected abstract void doTaskWork();
#Override
public void run() {
isDone = false;
doTaskWork();
isDone = true;
}
}
usage:
TimerTask myTask = new NonInterruptableTask() {
#Override
public void doTaskWork() {
//job here
}
};
you could also declare a boolean state called like "timerstate" or whatever and make it by default to be false. whenever you start a timer you could change this boolean to true and you'd be able to keep track of the timer.
public boolean timerstate;
public Timer t1;
// some code goes here to do whatever you want
if(timerstate == true) {
t1.cancel();
t1.purge();
t1 = new Timer();
} else{
t1.schedule(new TimerTask() {
#Override
public void run() {
timerstate = true;
//rest of code for the timer goes here
}
}
}

Java Countdown ends without returning into the main

I've got a program that controls an electronic component. My problem is the part with the countdown. Practically if I call the class CountDown from the main method, it won't return to the main. The program must be always active and it reads the first value in the main for call and start the countdown.
This is the code:
public class CountDown
{
public static int a;
public static Timer timer;
public CountDown()
{
timer = new Timer();
timer.schedule(new DisplayCountdown(), 0, 1000);
}
class DisplayCountdown extends TimerTask
{
int seconds = 15;
public void run()
{
if (seconds > 0)
{
System.out.println(seconds + " seconds remaining");
if(READING BY ELECTRONIC COMPONENT == 1)
{
seconds=15;
} else {
seconds--;
}
} else {
System.out.println("Countdown finished");
CountDown.a=0;
}
}
}
public static void main(String args[])
{
CountDown.a = 0;
while(true)
{
if(READING ELECTRONIC COMPONENT == 1)
{
if (CountDown.a==0)
{
CountDown.a = 1;
new CountDown();
}
}
}
}
I've checked to make sure my suspicions are correct. It's not that your new Countdown() isn't returning to the main method, it's that it returns immediately. What you want is likely to do some kind of waiting in the while(true) loop and checking whether or not the countdown is completed. Something along the lines of:
CountDown countDown = null;
while(true)
{
if (countDown == null || getReading() == 1)
{
if (CountDown.a == 0)
{
CountDown.a = 1;
countDown = new CountDown();
}
}
while (countDown.isRunning())
{
try
{
Thread.sleep(countDown.getRemainingSeconds() * 1000);
}
catch (InterruptedException ex)
{
// Ignore.
}
}
}
Obviously you'll need to implement the isRunning and getRemainingSeconds methods (you could always sleep for a set amount rather than trying to wait exactly the right amount of time if you want).
I'd also recommend trying to make this class better suited for re-use by avoiding the static variables a and timer (use private variables and setters/initialise them in the constructor instead).

Categories