MultiThreading with for loops in Java [closed] - java

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
Alright so i have been trying to run a for loop that runs 60 times. In this for loop i am using Thread.sleep(2000); to ping a server. I want to do this 10 times for this thread but for a separate loop through the for loop. In the mean time i want another 6 threads running doing 10 of their own so this hole process is sped up and completed in around 12 seconds.
for(int i = 0; i < 6; i++) {
//I am starting a new thread here.
}
#Override
public void run() {
//THIS is where i want a each thread to be doing 10 each to speed up the process.
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
I am sorry if this is hard to understand but i tried setting this out in the simplest way possible.
Thanks in advance.

If I get You right, You are not depending on the results, right? Here is a quick handdraft made out of the code:
Thread[] t = new Thread[6];
for(int i = 0; i < 6; i++) {
t[i] = new Thread() {
#Override
public void run() {
for(int i = 0; i < 60; i++) {
//Pinging server.
Thread.sleep(2000L);
//Gets info from server here. That is why there is a 2 second delay.
}
}
};
t[i].start();
}
Thread.sleep(longEnough);
This is the cheapest variant for kicking off threads, but beware, it is not professional! You should at least loop over the thread array to call join() on them in order to wait long enough instead of using a time constant.
If You want to do serious threading please consider using Java's ExecutorService (see http://www.vogella.com/tutorials/JavaConcurrency/article.html#threadpools) or ForkJoin of Java 7 (http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html)

In your initial for loop, instead of creating Threads, you should be creating Callable instances. Add these into a List, create an Executor, and pass the List to the Executor (FixedThreadPool for example). Then execute the Executor and they'll run in parallel. After all these hints, Ill leave the implementation to you since this looks sneakingly like a homework question.

Related

How to create a stopwatch with at least 98% accuracy and which shows 1/100th of second as well? [closed]

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 6 years ago.
Improve this question
I think that this type of question has already been asked but I could not related to any of those questions. I created a stopwatch
and it incremented every 1/100th seconds but that was far from accurate it was not even 60% accurate , I used hanlder.post and handler.post(...., 10).
Use timer. If you using handler.postDelay the problem is the next catch up will be delay few millisecond. It will be a big problem when you running like 1000 second.
Timer timer = new Timer(); //init the timer
Handler handler = new Handler();
int counter = 0; //counter to indicate the total second whenever timer fire
timerTask task = new timerTask();
timer.scheduleAtFixedRate(task,500,1000); //(which task to run,forget the usage try google, looping must be milisecond eg.1000 = 1 second)
private class timerTask extends TimerTask{
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
counter++;
if(counter >= 100){
//do something
}
}
});
}
}
You could take a look with alarm manager as well. But I didn't know wether it is helpful for you or not.

Blinking integers in Java [closed]

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 8 years ago.
Improve this question
I want to make a program that displays random numbers, bliking one at a time in a JLabel or just in the console. I am making a game, where the player needs to remember the number that was displayed two blinks back in time.
Does anyone know how to make the numbers blink?
I unfortunately don't have any GUI project handy to test it out (I might in a moment as a command line one), but I think that one way to do it is:
(I've removed the HideTask, as it gives some trouble when you want to run it again, and I don't think the task at hand really needs it - just call sleep() :) )
class ShowTask extends TimerTask {
JLabel label;
Random generator = new Random();
//HideTask hTask;
//java.util.Timer timer = new java.util.Timer();
long period = 500; // ms
public Task(JLabel pLabel){
label = pLabel;
//hTask = new HideTask(pLabel);
}
public void run(){
int i = generator.nextInt(100);
setLabel(i);
// if you want it to go SHOW HIDE SHOW HIDE instead of SHOW SHOW SHOW then:
//timer.schedule(hTask, period);
// just wait
Thread.sleep(period);
hideLabel();
}
void setLabel(int i){
...
}
}
/*
class HideTask extends TimerTask {
JLabel label;
public HideTask(JLabel pLabel){
label = pLabel;
}
public void run(){
hideLabel();
}
void hideLabel(){
...
}
}
*/
when you want to start:
ShowTask task = new ShowTask();
long delay = 0; // ms
long period = 1000; // ms
java.util.Timer timer = new java.util.Timer();
timer.scheduleAtFixedRate(task, delay, period);
Note, that it wasn't tested and it is just the first concept I come up with, but maybe you can work forward from it.

MultiThreading Query in java

I went for an interview and there i faced one question which is something like this.
int RetrieveAmount(String User) Throws UnableToRetrieveAmountException() {
int amount = 0;
int amount1 = RetrieveFromSystem1(User);
int amount2 = RetrieveFromSystem2(User);
amount = amount1+amount2;
return amount;
}
RetrieveAmount is a syncronozed function
1). Modify the code such that RetrieveFromSystemX(String user) should run independent of each other i.e. if the 1st one is taking 10 seconds and second function also takes 10 second to execute then they should be run in parallel.
2). RetrieveFromSystemX() is taking more time then a time out should happen.
Could anyone give me some pointers on this.
For the first part, I can use the executors with fixed thread pool of number of threads as 2 and can have two separate locks locking each one of these functions. Now two threads can act in parallel to RetrieveAmount(). Please let me know if i am thinking in the rite direction or not.
Could anyone guide me of the 2nd part of the question.
1) Both RetrieveFromSystem1(user) and RetrieveFromSystem2(user) can have there own threads started in the body of the methods. And there is no restriction on these two to be synchronized, it should work.
2) The thread class should have code like
long startTime = System.currentTimeMillis(); while(true) { if( System.currentTimeMillis - startTime < 10000) psudeocode: getData(); else Thread.currentThread().interrupt()};
In its run()

(Java Game Modding)How to delay this with nano time?

I'm programming a forcefield mod for Minecraft(a game.)
Here is my code so far:
if (Camb.killaura)
{
for(final int i= 0; i < mc.theWorld.loadedEntityList.size(); i++){
if((Entity)mc.theWorld.loadedEntityList.get(i) != this && getDistanceSqToEntity((Entity)mc.theWorld.loadedEntityList.get(i)) < 19.5D){
if(((Entity)mc.theWorld.loadedEntityList.get(i) instanceof EntityPlayer)){
mc.playerController.attackEntity(this, (Entity)mc.theWorld.loadedEntityList.get(i));
swingItem();
}
}
Everything works, but the issue is most servers only allow you to attack an entity 8 times a second. So my question is, how can I execute the following every .125 seconds? I asked a few fellow modders and they say they use nanoseconds, how can I do this?
This is the only code that needs the delay:
mc.playerController.attackEntity(this, (Entity)mc.theWorld.loadedEntityList.get(i));
swingItem();

Delays between Iterations of a for-loop in GWT

I'am strugeling with making delays in GWT (client-side).
What I want is to have a break of a few seconds between the iterations of a for-loop.
The first iteration should start instantly, but there has to be a pause between the following ones.
Anyone an idea?
You can delay by using Timer.
Try something like this:
Timer timer = new Timer() {
public void run {
// Whatever code you want to repeat
}
};
for(int i=0; i<10; i++) {
timer.schedule(100) //100 millisecond delay
}
Threading concept could be used for your question
you could try having a counter of loop and check for condition inside loop that if counter is >1 the use thread sleep for some seconds...

Categories