Java help: running 2 loops interconnected. scanner with while - java.util.scanner

Can anyone guide me on this, please?
The main idea is to have 2 loops which are called to run
public class time9 {
static void userInput() {
Scanner input = new Scanner(System.in);
String input2check = input.next();
//condition when there is an input to stop loop
}
static void timeUnit() {
for(int i = 1; i<60; i++) {
**//this makes seconds, minutes and hours**
}
}
public static void main(String[] args) {
for (int i = 1; i<60; i++){
userInput(input2check);
timeUnit(i);
**// for every i in timeUnit check user input.
// if no user input, time loop continues
// if there is user input, stop time loop**
}
}
}

You declare static void userInput() as taking no parameters, but you attempt to pass in 1 parameter: userInput(input2check). You should also make userInput
static boolean userInput(), because you are looking for a true/false statement as to whether the loop should break. Therefore, in your second for loop, you would have an if statement referring to userInput():
public class time9 {
static boolean userInput() {
Scanner input = new Scanner(System.in);
String input2check = input.next();
return (input2check != null);
/*true/false statement: return whether input2check is not null. Return true if not null, false otherwise.*/
}
static void timeUnit() {
for(int i = 1; i<60; i++) {
**//this makes seconds, minutes and hours**
}
}
public static void main(String[] args) {
for (int i = 1; i<60; i++){
if (userInput()){break;}
else{timeUnit);
}
}
}
You again tried to pass parameter i into static void timeUnit() which takes no parameters. Don't do it. Either declare a method like
[accessModifier] [returnType] [methodName] (parameter(s)),
and call it as [methodName](parameters)
or declare it as [accessModifier] [returnType] [methodName](), and call it as [methodName]().
If you pass params into a method that takes none, it has no algorithm to deal with those params and will not compile. If you pass no params into a method that takes params, it will not have an algorithm to deal with the lack of params, and will not compile.
Lastly, please know that your time loop should have nothing to do with the number 60 except by coincidence. Iterating 60 times through a for loop will NOT take 60 seconds. For loops can iterate several hundreds of thousands of times per second, so your 60 iteration for loop would take a matter of nanoseconds, unless you are using something like Thread.sleep(millis, nanos) which pauses the process for the milliseconds and nanos you set it to.

Related

Getting value from thread running in while loop

I have a java thread which is running a path-finding algorithm in a constant while loop. Then, every so often I want to retrieve the most updated path from the thread. However, I am unsure how to do this, and think I might be doing it wrong.
My thread consists of the following code:
public class BotThread extends Thread {
Bot bot;
AStar pathFinder;
Player targetPlayer;
public List<boolean[]> plan;
public BotThread(Bot bot) {
this.bot = bot;
this.plan = new ArrayList<>();
pathFinder = new AStar(bot, bot.getLevelHandler());
}
public void run() {
while (true) {
System.out.println("THREAD RUNNING");
targetPlayer = bot.targetPlayer;
plan = pathFinder.optimise(targetPlayer);
}
}
public boolean[] getNextAction() {
return plan.remove(0);
}
}
I then create an object of BotThread, and call start(). Then when I call getNextAction() on the thread, I seem to receive a null pointer. Is this because I am not able to call another method on the thread whilst it is in the main loop? How should I do this properly?
This is because you are not giving enough time to thread to initialise plan Arraylist. You need to add sleeping time to the threads. Something like this while calling BotThread class from main:
int num_threads = 8;
BotThread myt[] = new BotThread[num_threads];
for (int i = 0; i < num_threads; ++i) {
myt[i] = new BotThread();
myt[i].start();
Thread.sleep(1000);
myt[i].getNextAction();
}

Wait() in Haxe?

I am getting started with Haxe and OpenFl, and have some experience with Javascript and Lua.
It was going pretty well, till I got to a point where I needed a function similar to wait() in Lua, etc, which stops the script until the number of seconds you set is over.
How would I go about doing this?
EDIT: To clarify, I am building to Flash.
Although this is old, I wanted to add another point for reference. The OP mentioned in a comment this was for a game. One method I often use is (and could probably be put in a library):
var timerCount:Float = 0;
var maxTimerCounter:Float = 5;
function update () {
timerCounter += elapsedTime;
if (timerCounter > maxTimerCounter){
onTimerComplete();
timerCount = 0;
}
}
In SYS you are looking for:
static function sleep( seconds : Float ) : Void
Suspend the current execution for the given time (in seconds).
Example: Sys.sleep(.5);
http://haxe.org/api/sys/
Edit: User is porting to flash.
So the suggestion is to use Timer
http://haxe.org/api/haxe/timer
In Timer the suggestion is to use
static function delay( f : Void -> Void, time_ms : Int ) : Timer
Someone on stack overflow has an example that looks like this: haxe.Timer.delay(callback(someFunction,"abc"), 10); located here... Pass arguments to a delayed function with Haxe
For the Flash compile target, the best you can do is use a timer, and something like this setTimeout() function.
This means slicing your function into two - everything before the setTimeout(), and everything after that, which is in a separate function that the timeout can call.
so somethine like, eg:
tooltipTimerId = GlobalTimer.setTimeout(
Tooltip.TOOLTIP_DELAY_MS,
handleTooltipAppear,
tootipParams
);
[...]
class GlobalTimer {
private static var timerList:Array<Timer>;
public static function setTimeout(milliseconds:Int, func:Dynamic, args:Array<Dynamic>=null):Int {
var timer:Timer = new Timer(milliseconds);
var id = addTimer(timer, timerList);
timer.run = function() {
Reflect.callMethod(null, func, args);
clearTimeout(id);
}
return id;
}
private static function addTimer(timer:Timer, arr:Array<Timer>):Int {
for (i in 0...arr.length) {
if (null == arr[i]) {
arr[i] = timer;
return i;
}
}
arr.push(timer);
return arr.length -1;
}
public static function clearTimeout(id:Int) {
var timers:Array<Timer> = GlobalTimer.getInstance().timerList;
try {
timers[id].stop();
timers[id] = null;
} catch(e:Error) {/* Nothing we can do if it fails, really. */}
}
}

Multithreading and Monitoring

I am trying to get multithreading more unraveled in my head. I made these three classes.
A global variable class
public partial class globes
{
public bool[] sets = new bool[] { false, false, false };
public bool boolChanged = false;
public string tmpStr = string.Empty;
public int gcount = 0;
public bool intChanged = false;
public Random r = new Random();
public bool gDone = false;
public bool first = true;
}
Drop in point
class Driver
{
static void Main(string[] args)
{
Console.WriteLine("start");
globes g = new globes();
Thread[] threads = new Thread[6];
ParameterizedThreadStart[] pts = new ParameterizedThreadStart[6];
lockMe _lockme = new lockMe();
for (int b = 0; b < 3; b++)
{
pts[b] = new ParameterizedThreadStart(_lockme.paramThreadStarter);
threads[b] = new Thread(pts[b]);
threads[b].Name = string.Format("{0}", b);
threads[b].Start(b);
}
}
}
And then my threading class
class lockMe
{
#region Fields
private string[] words = new string[] {"string0", "string1", "string2", "string3"};
private globes g = new globes();
private object myKey = new object();
private string[] name = new string[] { String.Empty, String.Empty, String.Empty };
#endregion
#region methods
// first called for all threads
private void setName(Int16 i)
{
Monitor.Enter(myKey);
{
try
{
name[i] = string.Format("{0}:{1}", Thread.CurrentThread.Name, g.r.Next(100, 500).ToString());
}
finally
{
Monitor.PulseAll(myKey);
Monitor.Exit(myKey);
}
}
}
// thread 1
private void changeBool(Int16 a)
{
Monitor.Enter(myKey);
{
try
{
int i = getBools();
//Thread.Sleep(3000);
if (g.gcount > 5) { g.gDone = true; return; }
if (i == 3) resets();
else { for (int x = 0; x <= i; i++) { g.sets[x] = true; } }
Console.WriteLine("Thread {0} ran through changeBool()\n", name[a]);
}
finally
{
Monitor.PulseAll(myKey);
Monitor.Exit(myKey);
}
}
}
// thread 2
private void changeInt(Int16 i)
{
Monitor.Enter(myKey);
{
try
{
g.gcount++;
//Thread.Sleep(g.r.Next(1000, 3000));
Console.WriteLine("Thread {0}: Count is now at {1}\n", name[i], g.gcount);
}
finally
{
Monitor.PulseAll(myKey);
Monitor.Exit(myKey);
}
}
}
// thread 3
private void printString(Int16 i)
{
Monitor.Enter(myKey);
{
try
{
Console.WriteLine("...incoming...");
//Thread.Sleep(g.r.Next(1500, 2500));
Console.WriteLine("Thread {0} printing...{1}\n", name[i], words[g.r.Next(0, 3)]);
}
finally
{
Monitor.PulseAll(myKey);
Monitor.Exit(myKey);
}
}
}
// not locked- called from within a locked peice
private int getBools()
{
if ((g.sets[0] == false) && (g.sets[1] == false) && (g.sets[2] == false)) return 0;
else if ((g.sets[0] == true) && (g.sets[1] == false) && (g.sets[2] == false)) return 1;
else if ((g.sets[2] == true) && (g.sets[3] == false)) return 2;
else if ((g.sets[0] == true) && (g.sets[1] == true) && (g.sets[2] == true)) return 3;
else return 99;
}
// should not need locks- called within locked statement
private void resets()
{
if (g.first) { Console.WriteLine("FIRST!!"); g.first = false; }
else Console.WriteLine("Cycle has reset...");
}
private bool getStatus()
{
bool x = false;
Monitor.Enter(myKey);
{
try
{
x = g.gDone;
}
finally
{
Monitor.PulseAll(myKey);
Monitor.Exit(myKey);
}
}
return x;
}
#endregion
#region Constructors
public void paramThreadStarter(object starter)
{
Int16 i = Convert.ToInt16(starter);
setName(i);
do
{
switch (i)
{
default: throw new Exception();
case 0:
changeBool(i);
break;
case 1:
changeInt(i);
break;
case 2:
printString(i);
break;
}
} while (!getStatus());
Console.WriteLine("fin");
Console.ReadLine();
}
#endregion
}
So I have a few questions. The first- is it better to have my global class set like this? Or should I be using a static class with properties and altering them that way? Next question is, when this runs, at random one of the threads will run, pulse/exit the lock, and then step right back in (sometimes like 5-10 times before the next thread picks up the lock). Why does this happen?
Each thread is given a certain amount of CPU time, I doubt that one particular thread is getting more actual CPU time over the others if you are locking all the calls in the same fashion and the thread priorities are the same among the threads.
Regarding how you use your global class, it doesn't really matter. The way you are using it wouldn't change it one way or the other. Your use of globals was to test thread safety, so when multiple threads are trying to change shared properties all that matters is that you enforce thread safety.
Pulse might be a better option knowing that only one thread can actually enter, pulseAll is appropriate when you lock something because you have a task to do, once that task is complete and won't lock the very next time. In your scenario you lock every time so doing a pulseAll is just going to waste cpu because you know that it will be locked for the next request.
Common example of when to use static classes and why you must make them thread safe:
public static class StoreManager
{
private static Dictionary<string,DataStore> _cache = new Dictionary<string,DataStore>(StringComparer.OrdinalIgnoreCase);
private static object _syncRoot = new object();
public static DataStore Get(string storeName)
{
//this method will look for the cached DataStore, if it doesn't
//find it in cache it will load from DB.
//The thread safety issue scenario to imagine is, what if 2 or more requests for
//the same storename come in? You must make sure that only 1 thread goes to the
//the DB and all the rest wait...
//check to see if a DataStore for storeName is in the dictionary
if ( _cache.ContainsKey( storeName) == false )
{
//only threads requesting unknown DataStores enter here...
//now serialize access so only 1 thread at a time can do this...
lock(_syncRoot)
{
if (_cache.ContainsKey(storeName) == false )
{
//only 1 thread will ever create a DataStore for storeName
DataStore ds = DataStoreManager.Get(storeName); //some code here goes to DB and gets a DataStore
_cache.Add(storeName,ds);
}
}
}
return _cache[storeName];
}
}
What's really important to see is that the Get method only single threads the call when there is no DataStore for the storeName.
Double-Check-Lock:
You can see the first lock() happens after an if, so imagine 3 threads simultaneously run the if ( _cache.ContainsKey(storeName) .., now all 3 threads enter the if. Now we lock so that only 1 thread can enter, now we do the same exact if statement, only the very first thread that gets here will actually pass this if statement and get the DataStore. Once the first thread .Add's the DataStore and exits the lock the other 2 threads will fail the second check (double check).
From that point on any request for that storeName will get the cached instance.
So we single threaded our application only in the spots that required it.

How to grab value from a thread?

Hi i am trying to grab a value from my threading but it seem work not so find to me course i found that my code structure are unstable enough..here is my code i name my thread class as "clsThreadCount" and below is my implementation
public volatile bool Grab = false;
public volatile int count = 0;
public void Initialization(int i)
{
count = i;
}
public void Play()
{
Grab = false;
_shouldStop = false;
ThreadTest();
}
public void Stop()
{
_shouldStop = true;
workerThread.Join(1);
workerThread.Abort();
}
private void ThreadTest()
{
workerThread = new Thread(DoWork);
workerThread.Start();
while (!workerThread.IsAlive) ;
}
private void DoWork()
{
try
{
while (!_shouldStop)
{
if (Grab)
{
count++;
Grab = false;
}
}
}
catch (Exception)
{
Play();
}
finally
{
}
}
when my program(main menu) are starting to run i will trigger the initialize function at pass the parameter as 7
ObjThreadCount.Initialization(7); // count = 7
ObjThreadCount.Play(); // the thread are running
ObjThreadCount.Grab = true; // the grab equal to true, count++ are trigger
Thread.Sleep(100); // wait awhile
lblResult.Text = ObjThreadCount.count.ToString(); // sometime i can get count++ result (e.g. 8)
ObjThreadCount.Stop(); // thread stop
sometime my program can able to get a right counting from the thread but sometime are not.
i realize at my while loop implementation there are something are missing..
something like waitone or waitautoevent..can i ignore Thread.Sleep(100) ?? what are the suitable code should i add in the while loop ?
Please help me~ :S
** sorry in the first upload i forgot to write down "volatile" into the variable
thank you..
If C# (and C and java, and probably C++), you need to declare _shouldStop and Grab as volatile.

Neko and haxe.Timer.delayed()

As every Haxe developer knows, you could use haxe.Timer.delayed() to delay function call for some time. But this function doesn't exist for Neko at all. Is there a way to achieve the same results?
Have to check it first but
function delayed(f, time) {
neko.vm.Thread.create(function() {
neko.Sys.sleep(time);
f();
});
}
might be the closest thing possible. The only cons is that application becomes multi threaded which could lead to serious problems.
I thought about your issue and I think the best way is to create your own Timer class for Neko. I made a Timer class for you:
NekoTimer.hx
package;
import neko.Sys;
class NekoTimer
{
private static var threadActive:Bool = false;
private static var timersList:Array<TimerInfo> = new Array<TimerInfo>();
private static var timerInterval:Float = 0.1;
public static function addTimer(interval:Int, callMethod:Void->Void):Int
{
//setup timer thread if not yet active
if (!threadActive) setupTimerThread();
//add the given timer
return timersList.push(new TimerInfo(interval, callMethod, Sys.time() * 1000)) - 1;
}
public static function delTimer(id:Int):Void
{
timersList.splice(id, 1);
}
private static function setupTimerThread():Void
{
threadActive = true;
neko.vm.Thread.create(function() {
while (true) {
Sys.sleep(timerInterval);
for (timer in timersList) {
if (Sys.time() * 1000 - timer.lastCallTimestamp >= timer.interval) {
timer.callMethod();
timer.lastCallTimestamp = Sys.time() * 1000;
}
}
}
});
}
}
private class TimerInfo
{
public var interval:Int;
public var callMethod:Void->Void;
public var lastCallTimestamp:Float;
public function new(interval:Int, callMethod:Void->Void, lastCallTimestamp:Float) {
this.interval = interval;
this.callMethod = callMethod;
this.lastCallTimestamp = lastCallTimestamp;
}
}
Call it like this:
package ;
import neko.Lib;
class Main
{
private var timerId:Int;
public function new()
{
trace("setting up timer...");
timerId = NekoTimer.addTimer(5000, timerCallback);
trace(timerId);
//idle main app
while (true) { }
}
private function timerCallback():Void
{
trace("it's now 5 seconds later");
NekoTimer.delTimer(timerId);
trace("removed timer");
}
//neko constructor
static function main()
{
new Main();
}
}
Hope that helps.
Note: this one has an accuracy of 100ms. You can increase this by decreasing the timerInterval setting.
I used the class as well, and I found one issue. Because is not completely realtime, it sleeps the interval, calls the function, and sleeps the interval again. So, depending on how long the function you are running takes, it ticks slower or faster.
I've solved it by replacing line 39 like so:
//timer.lastCallTimestamp = Sys.time() * 1000;
timer.lastCallTimestamp = timer.lastCallTimestamp + timer.interval;
Yes I don't know anything except for what you mention in your first answer. On Linux you can use SIGALARM - but this doesn't look trivial, 100% pure C code, and needs to be handled with great care to avoid crashing the VM.

Resources