Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I need to create a delay during my loop so that the loop only changes the color of the bossbar every 2 seconds, but I can't use Thread.sleep because that pauses the entire server and eventually crashes it. How do I create a delay like this? Surely there's just a simple 1 line method I can call to do this, I mean with Python all I have to do is type 'sleep(2)'.
If you are using bukkit try to call the scheduler to make the task run on a timer
this is a link for an in-depth explanation -> tutorial
here is some code for creating a delayed task
public void methodThatChangesBossbar() {
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
//decrease bossbar health here....
//when your finished with this method just use 'return' to break the loop.
}, [put delay before each time this method runs, 2000 = 2 seconds], [offset before method first runs];
}
remember the last arguments are time expressed in milliseconds
try this
Runnable runnable2 = new Runnable() {
#Override
public void run() {
try {
Thread t = Thread.currentThread();
System.out.println("Runnable: " + t);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(runnable2);
t.start();
Related
This question already has answers here:
How Thread.sleep() works internally
(5 answers)
Closed 3 years ago.
It may be a dumb question but i have researched it alot and i am not getting any satisfactory knowledge.
Can anyone help me to understand?
my code
public class sleepclass extends Thread {
public static void main(String[] args) {
sleepclass t1 = new sleepclass();
sleepclass t2 = new sleepclass();
t1.start();
t2.start();
}
public void run() {
for (int i = 1; i < 5; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
}
Output :
1
1
2
2
3
3
4
4
Now as per the output i can see both thread gone to a sleep state. and both comes after at the same time
My question is :
1 . Since sleep is a static method how both works and sleep at same time? (explain in layman please).
Can i sleep only t1 and left t2 to run?
Thread.sleep() sleeps the current thread. It has no effect elsewhere.
If you want one thread to sleep and one not in your current code, you would have to have some kind of indicator to control it. Such as a boolean flag which you would then check:
if(shouldSleep) {
Thread.sleep(5000);
}
Otherwise all threads will execute the same code, and all threads will sleep for 5 seconds.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I"M TRYING TO PUT A 5 SECONDS GAP BETWEEN 2 THREADS,THAT RUNS ONE AFTER ANOTHER I.E. SUPPOSE MY 1ST THREAD PRINTS "X" ,THERE WILL BE 5 SECONDS DELAY & THEN ANOTHER THREAD IS PRINTED "Y", AGAIN 5 SECONDS DELAY & THEN "X" & THIS IS GOES ON , SAY 30 TIMES.
import java.lang.*;
import java.util.concurrent.TimeUnit;
class PingPong implements Runnable
{ String word;
PingPong(String s){
word = s;
}
public void run()
{
try
{
for(int i = 0; i<30; i++)
{
System.out.println(word);
Thread.sleep(100) ;
}
} catch (InterruptedException e)
{ e.printStackTrace(); }
}
public static void main(String[] args){
Runnable p1 = new PingPong("ping");
Thread t1 = new Thread(p1);
t1.start();
Runnable p2 = new PingPong("pong");
Thread t2 = new Thread(p2);
t2.start();
}
}
Threads are independent of each other unless you introduce some kind of synchronisation mechanism. So the first thing you need to do is change your PingPong class to take something to synchronize on, on which each thread is going to wait.
Let's call this object ball. You can pass it in the constructor of PingPong. It can be any object you want (even just Object) or you can create your own small class for it.
Then in your loop, you can do:
synchronized(ball) {
System.out.println(word);
Thread.sleep(5000);
}
Thread.sleep(1000);
This way each thread will block for 5seconds until it allows another thread to 'take' the ball's monitor and output it's word.
The second sleep is arbitrary but important so that the same thread doesn't get the monitor again.
A slightly more complex but more correct way to do it is to use a second ReentrantLock. Again you have to pass it through the constructor together with the previous ball object. Let's call this lock.
lock.lock();
synchronized(ball) {
try {
System.out.println(word);
} finally {
lock.unlock();
}
Thread.sleep(5000);
}
The unlock() is in a finally block to ensure that if any exception is thrown the lock doesn't remain locked forever.
The System.out didn't actually need to be inside the try block, but this makes the code a bit more elegant, rather than having an empty try. The sleep() has to be outside, to make sure the other thread goes in through the first lock while this thread is sleeping.
This ensures that if thread Ping is sleeping, thread Pong takes the lock, so it will be next to go inside the synchronized block. When Ping wakes up and goes out of the synchronized block, even if coincidentally gets scheduled before Pong, it won't be able to proceed because it can't take the lock, and has to wait for Pong to go inside the synchronized block and output its word.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I was digging around in some old java projects that I never finished and I pulled out this little number that is of my best projects ever built.
It's a desktop clock widget coded in java and it works perfectly fine except for one thing. The way I have it check the current time to stay updated is in a loop and the loop "crashes" in a matter of seconds so the widget no longer gets the current time.
This is how the loop is constructed (reduced in size):
public class getCurrentTime {
public static void getTime() throws InterruptedException {
int hour = global.calendar.get(Calendar.HOUR);
int minute = global.calendar2.get(Calendar.MINUTE);
if(hour == 0) {
global.hour.setIcon(new ImageIcon("resources/hours/12.png"));
}else if(hour == 23) {
global.hour.setIcon(new ImageIcon("resources/hours/11.png"));
}else {
global.hour.setText("?");
}
if(minute == 0) {
global.minute.setIcon(new ImageIcon("resources/minutes/00.png"));
}else if(minute == 59) {
global.minute.setIcon(new ImageIcon("resources/minutes/59.png"));
}else {
global.minute.setText("?");
}
Thread.sleep(1000);
getTime();
}
}
global is a class where I keep most of my variables (I know it's weird, this was like 3 years ago, it's how I used to write my programs).
So my main question is, is there a way that I can prevent the loop from "crashing"?
Thanks in advance!
This is not a loop, really. It is a recursive call. In each recursion, some more memory will be allocated, so it will after some time go out of memory. I wonder why this is a matter of seconds here, but anyway.
Try using a Timer to schedule the gui update.
Edit : you are creating a new ImageIcon in each recursion. They can be rather large in memory. Maybe they are the reason for the rapid "crash".
Apart from that I suggest sticking to java naming conventions. Class names should start with a capital letter.
Thread.sleep(1000); is not going to be a good option. You can use Timer. By using a Timer you schedule a task at regular intervals.
Timer timer = new Timer();
long interval = (1000) ; // 1 sec
timer.schedule( new TimerTask() {
public void run() {
//do your work;
}
}, 0, interval);
If you want to stop the scheduling, you can use timer.cancel();
EDIT: as Fildor said I think memory is your problem. Use timer this way, it should solve your problem.
This is first solution
class clockUpdater implements Runnable {
#Override
public void run() {
Thread.sleep(WAIT_TILL_NEW_MINUTE);
while(true){ //a infinite loop
// the Swing call below must be queued onto the Swing event thread
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
//your clock updating code here
}
});
try {
Thread.sleep(1000*60);//you only need to update once after a minute
} catch (InterruptedException e) {
// ....
}
}
}
}
This is second
class clockUpdater extends Thread{
#Override
public void run(){
Thread.sleep(WAIT_TILL_NEW_MINUTE);
while(true){
try{
//your update code here
Thread.sleep(60*1000)//
}
catch(Exception e){
//..
}
}
}
}
Note: You need to start this as soon as the minute changes in system time. Or clock time will lag behind. Calculate WAIT_TILL_NEW_MINUTE as soon as your program starts. Better to update only when it is needed.
The answer for your question is
use set timeout function for the function
which you want to avoid loop crashing.
Like:
setTimeout(function() {
// write the logic
},1000);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following code:
class Hi
{
public static void main (String [] args)
{
int a = 1;
for (int i = 0; i < 50; i++) {
a = a + i;
System.out.println ("a before sleep is " + a);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
}
System.out.println ("a after sleep is " + a);
}
}
}
I open two console windows and do java Hi in first one. Then wait for about 10 seconds seconds and do the same in the second window. Both outputs are the same:
a before sleep is 1
a after sleep is 1
a before sleep is 2
a after sleep is 2
a before sleep is 4
a after sleep is 4
a before sleep is 7
a after sleep is 7
a before sleep is 11
a after sleep is 11
with no interleaving. So what's the stir about concurrency issues if I even didn't bother to use synchronized statement? Is it because the code run from different console windows is executed on different processor cores? If so, I've carried out this experiment about 20 times and the results are still the same.
I open two console windows and do java Hi in first one. Then wait for about 10 seconds seconds and do the same in the second window.
You're starting two entirely separate process. That's not using multithreading at all - each process will have its own variables, its own output, everything.
To see multithreading, you need to create threads in a single process. For example:
import java.util.Random;
class Counter implements Runnable {
private int a;
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
String name = Thread.currentThread().getName();
a++;
System.out.println(name + " Before sleep, a = " + a);
try {
// Add a little more uncertainty...
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
// Ignored
}
System.out.println(name + " After sleep, a = " + a);
}
}
}
public class ThreadingTest {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(counter);
Thread t2 = new Thread(counter);
t1.start();
t2.start();
}
}
You have two different JVM's so two main threads running on two different JVM's so concurrency dont apply.
Yes if you have two threads within same JVM then concurrency applies.
These are two separate processes on your computer. They do not share data or anything else. They are no more related then, for example, your web browser and your wordprocessor. They each have their own separate "a" variable, each completely unrelated to the other.
Concurrency issues arise when multiple threads in the same process space try to access the same variable. That does not apply here.
As here you are running two different processes, no matter how many times you run this code you will get same result. As both of these programs will be running within two separate processes.
To run these programs in multi threaded way you have to implement two threads and start them.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Below is the code I am working with. I am new to programming and I know I need to use a loop to have the set velocities I have repeat four times, I am just not sure how to do it. Any help would be greatly appreciated!
package Code.simpleOutput;
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
public class GeoPattern {
public static void main(final String[] args)
{
Finch myFinch = new Finch();
myFinch.setWheelVelocities(255,255,1000);
myFinch.setWheelVelocities(255,0,800);
myFinch.setWheelVelocities(255,255,1000);
myFinch.setWheelVelocities(255,0,800);
myFinch.setWheelVelocities(255,255,1000);
myFinch.setWheelVelocities(255,0,800);
myFinch.setWheelVelocities(255,225,1000);
myFinch.quit();
System.exit(0);
}
}
Here's a for loop.
for(int x = 4; x >0; x--) {
myFinch.setWheelVelocities(255,255,1000);
myFinch.setWheelVelocities(255,0,800);
}
You need to explain your objective more though.
This code will set the wheel velocities to 255,255,1000, then immediately change them back to 255,0,800, and do that four times.
Aren't you instead trying to switch between them, which would require some kind of pause, timer, or test?
In the meantime, you really should peruse the Oracle documentation for Java, and in particular the control structures: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
If you are new to Java, Exceptions and Threads are probably a bit of a harsh takeoff, but bear with me:
Thread.sleep(4000);
This instruction will make your code pause for 4 seconds (it takes milliseconds as an argument).
In order to use that "pause" code, you'll need to declare that your method, here, main:
throws InterruptedException
Why? Because, if you had several "Threads" in your application, another Thread might interrupt yours while it is sleeping. Basically, say "hey, I need to calculate something, since you're asleep I'm going to borrow the processor, I'll give it back later"
Since you only have one Thread, you don't bother, you just declare that it might theorically happen, and you're good to go.
In the event that you wanted to switch the speeds and see it happen, the code becomes:
package Code.simpleOutput;
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
public class GeoPattern {
public static void main(final String[] args)
throws InterruptedException // because it contains a sleep call
{
Finch myFinch = new Finch();
for(int x = 4; x >0; x--)
{
Thread.sleep(1000); // sleep a second
myFinch.setWheelVelocities(255,255,1000);
Thread.sleep(1000); // sleep another second
myFinch.setWheelVelocities(255,0,800);
}
myFinch.quit();
System.exit(0);
}
}
Are you just looking for
for (int i = 0; i < 4; i++) {
myFinch.setWheelVelocities(255,255,1000);
myFinch.setWheelVelocities(255,0,800);
}
You could use a for loop
for(int i = 0; i < 4; i++)
{
//code to repeat goes here
}
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html