Python - Threading, Timing, or function use? - java

I am having an issue formulating an idea on how to work this problem. Please help.
My project consists of an N x N grid with a series of blocks that are supposed to move in a random direction and random velocity within this grid (every .1 seconds, the location of the block is updated with the velocity). I have three "special" blocks that are expected to have individual movement functions. I will have other blocks (many of them) doing nothing but updating their location, and making sure they remain in the grid.
Now these three blocks have functions beyond movement, but each of these runs individually, waiting for the other block's special function to finish (block 2 will wait on block 1, Block 3 will wait on 2 and set it back to block 1, etc.) This queue of sorts will be running while the motion is happening. I want the motion to never stop. After each block's non-movement function runs n times, the code finishes.
My question is this: should I use threads to start and stop the non-movement functions, or is there a way to just set a time and set booleans that could use a class function after .1 seconds to continuously move the objects (and obviously loop over and over), and then use counts to end the program all together? If so, how would you write main function for this in Python? For all of this happening, does anyone think that Java would be significantly faster than Python in running this, especially if writing the data to a .txt file?

Your best bet is probably to handle all of them at once in a single update function rather than attempting to use Threads. This is primarily because the Global Interpreter Lock will prevent multiple threads from processing concurrently anyway. What you're after then is something like this:
def tick():
for box in randomBoxes:
box.relocate()
specialBlock1.relocate()
specialBlock2.relocate()
specialBlock3.relocate()
Then we define a second function that will run our first function indefinitely:
def worker():
while True:
tick()
sleep(0.1)
Now that we have an interval or sorts, we'll launch a Thread that runs in the background and handles our display updates.
from threading import Thread
t = Thread(target = worker, name = "Grid Worker")
t.daemon = True # Useful when this thread is not the main thread.
t.start()
In our tick() function we've worked in the requirements that specialBlocks 1, 2, and 3 are working in a set order. The other boxes each take their actions regardless of what the others do.

If you put the calls to the special functions together in a single function, you get coordination (2) for free.
def run(n, blocks):
for i in range(n):
for b in blocks:
b.special()
As for the speed of Python versus Java, it depends on many things, such as the exact implementation. There is too little information to say.

Related

Is drawing straight lines in paint using SHIFT and mouse dragging an example of multithreading?

I am studying multi-threading and now I am stuck. I read that Multi-threading in java is a process of executing multiple threads simultaneously. What does this 'simultaneously' mean? Also, multi-threading is based upon the concept of time-sharing, so how can the threads execute simultaneously? And if threads can't execute simultaneously, then how are we able to draw straight lines in paint by holding the shift key and dragging the mouse at the same time?
A short overview:
Indeed most Threads do not run at the same time. The trick is that threads switch often between one another. This gives the illusion of parallelism. (Similar to how images in quick succession give the illusion of continuous motion, quickly changing threads give the illusion of running at the same time)
How paint is implemented is anyone's guess. Here goes mine:
You press shift, a boolean flag gets raised
You move your mouse, the line is calculated
If you raise the shift key the bool flag is switched, causing the line not to be straight anymore
Ideed, key listening is an action that often is multithreaded. You have a thread that just asks all keys every few milliseconds if they were pressed. If so it sends a message to other treads (if they are listening for that particular key). The same goes for reading mouse movement.
Usually, you do not have to go in great detail for IO, as it is handled by most librarys/ frameworks for you. Also IO requires OS support, so that opens a new can of worms
I hope this helped
Processor can't execute several threads at one time, so threads are executing pseudo-simultaneously.
At this picture each color means each thread. Processor execute one thread then second etc. It seems like they are executing sumultaneously, but probably processor just change current thread and execute this.

Java Lejos autonomous NXJ-robot threads causing trouble

I'm writing an java code to control a fairly simple robot, which should execute the following actions; PID-linefollower, ultrasonic detection and color detection.
As this is my first program in java, I obviously have lots to learn in regards to OOP.
The robot runs on a track where the line is accompanied by colors on the road, which the robot should periodically check for and if found, act differently based on which color it reads.
So the process should run somewhat alike this following pseudo(java)-code:
Initialize and calibrate sensors.
while (! Button.ENTER.isDown)
Run PID-controller
If (ColorSensorColor = 0 || ColorSensorColor = 2)
if (color = 0)
turn left
if (color = 2)
turn right
while (UltraSonicDistance < 30cm)
free-roll motors
My question therefore is; how do I construct two threads that can run the ColorSensor and UltraSonicSensor in parallel with a main thread?
The latest actual code is situated here
Lastly, thanks for all your input - I've scoured the interwebz for good tutorials, but it seems that I have too few braincells to comprehend the mother of all OOP.
/u/evil_burrito on /r/javahelp kindle answered with the following, working suggestion:
First, you might want to consider a real time JVM, if you're not already. If your controller has to run uninterrupted, that might be something to consider. FWIW, RT is not my area of expertise at all.
However, your basic question about threads is easier to answer.
Create an inner class for each of the ultrasonic sensor and the color sensor. Have those classes implement Runnable. In the run method, check the appropriate sensor and update a volatile variable in the outer class.
Use a ScheduledExecutorService to execute a sensor check for each of these classes (create an instance of the inner class and submit it to the executor to be run at intervals of 1ms or 100 microseconds, or whatever).
The main class can just monitor the values of the volatile variables and decide what to do w/o interruption.

java application multi-threading design and optimization

I designed a java application. A friend suggested using multi-threading, he claims that running my application as several threads will decrease the run time significantly.
In my main class, I carry several operations that are out of our scope to fill global static variables and hash maps to be used across the whole life time of the process. Then I run the core of the application on the entries of an array list.
for(int customerID : customers){
ConsumerPrinter consumerPrinter = new ConsumerPrinter();
consumerPrinter.runPE(docsPath,outputPath,customerID);
System.out.println("Customer with CustomerID:"+customerID+" Done");
}
for each iteration of this loop XMLs of the given customer is fetched from the machine, parsed and calculations are taken on the parsed data. Later, processed results are written in a text file (Fetched and written data can reach up to several Giga bytes at most and 50 MBs on average). More than one iteration can write on the same file.
Should I make this piece of code multi-threaded so each group of customers are taken in an independent thread?
How can I know the most optimal number of threads to run?
What are the best practices to take into consideration when implementing multi-threading?
Should I make this piece of code multi-threaded so each group of customers are taken
in an independent thread?
Yes multi-threading will save your processing time. While iterating on your list you can spawn new thread each iteration and do customer processing in it. But you need to do proper synchronization meaning if two customers processing requires operation on same resource you must synchronize that operation to avoid possible race condition or memory inconsistency issues.
How can I know the most optimal number of threads to run?
You cannot really without actually analyzing the processing time for n customers with different number of threads. It will depend on number of cores your processor has, and what is the actually processing that is taking place for each customer.
What are the best practices to take into consideration when implementing multi-threading?
First and foremost criteria is you must have multiple cores and your OS must support multi-threading. Almost every system does that in present times but is a good criteria to look into. Secondly you must analyze all the possible scenarios that may led to race condition. All the resource that you know will be shared among multiple threads must be thread-safe. Also you must also look out for possible chances of memory inconsistency issues(declare your variable as volatile). Finally there are something that you cannot predict or analyze until you actually run test cases like deadlocks(Need to analyze Thread dump) or memory leaks(Need to analyze Heap dump).
The idea of multi thread is to make some heavy process into another, lets say..., "block of memory".
Any UI updates have to be done on the main/default thread, like print messenges or inflate a view for example. You can ask the app to draw a bitmap, donwload images from the internet or a heavy validation/loop block to run them on a separate thread, imagine that you are creating a second short life app to handle those tasks for you.
Remember, you can ask the app to download/draw a image on another thread, but you have to print this image on the screen on the main thread.
This is common used to load a large bitmap on a separated thread, make math calculations to resize this large image and then, on the main thread, inflate/print/paint/show the smaller version of that image to te user.
In your case, I don't know how heavy runPE() method is, I don't know what it does, you could try to create another thread for him, but the rest should be on the main thread, it is the main process of your UI.
You could optmize your loop by placing the "ConsumerPrinter consumerPrinter = new ConsumerPrinter();" before the "for(...)", since it does not change dinamically, you can remove it inside the loop to avoid the creating of the same object each time the loop restarts : )
While straight java multi-threading can be used (java.util.concurrent) as other answers have discussed, consider also alternate programming approaches to multi-threading, such as the actor model. The actor model still uses threads underneath, but much complexity is handled by the actor framework rather than directly by you the programmer. In addition, there is less (or no) need to reason about synchronizing on shared state between threads because of the way programs using the actor model are created.
See Which Actor model library/framework for Java? for a discussion of popular actor model libraries.

Separate processes, each run in multithread JAVA

I have 4 separate processes which need to go one after another.
1st process
2nd process
3rd process
4th process
Since, every process is connected to one another, each process should run after process before him finishes.
Each process has its own variable length which will be various as programs data input grows.
But some sketch would be like this
Program Runs
1st process - lasts 10 seconds
2nd process - has 300 HTTP get requests, last 3 minutes
3rd process - has 600 HTTP get requests, lasts 6 minutes
4th process - lasts 1 minute
Program is written in java
Thanks for any answer!
There is no concurrency support in the java API for your use case because what you're asking for is the opposite of concurrent. You have a set of four mutually dependent operations that need to be run in a specific order. You only need, and should probably only use, one thread to correctly handle this case.
It would be reasonable and prudent to put each operation in its own method or class, based on how complex the operations are.
If you insist on using multiple threads, your main thread should maintain a list of runnables. Iterate through the list. Pop the first runnable from the list, create a new thread for that runnable, start the thread, and then invoke join() on the thread. The main thread will block until the runnable is complete. The loop will take you through all the runnables in order. Again, there is no good reason to do this. There may or may not be a bad reason.

Java: How to interrupt a program partway through execution with a mouseclick

How would one go about implementing a mouselistener (or some other way, doesn't matter) that will handle a mouse click event at ANY part of the program? Preferably returning to the line it left off at when the click event handler method completes.
I am using swing. The 'context' is a GUI that constantly updates, but must respond to a mouse click from the user at any time with no delay. Indeed I do have experience with events, using and overwriting their handlers etc., not too in-depth I suppose but what i do know has been sufficient in anything until now.
I could not understand your first para, so my answer goes for your second para, if I understood that correctly. ;)
Swing follows single thread model. So, you should be updating the UI from Event Dispatch Thread (EDT). This thread is responsible for delivering the events to your code too, hence the name. If you are continuously updating an UI in a loop then that is going to keep the EDT busy and blocked. The end effect will be an UI which does not respond to user events. This because the events are getting queued and EDT can pick them and deliver them to your code when it becomes free.
Games typically encounter this kind of scenario. You might have noticed that games typically have one fixed rate of refresh which they call FPS (Frames Per Second). Typically maintaining 60 FPS is good enough. That is, you need to draw your UI 50 times per second, but right now it seems that your render loop (which updates the UI) is running continuously.
You need to have separate thread continuously running which is responsible for drawing the UI. This should draw into a buffer (Image). And then invoke repaint() on the UI element to be updated. That UI element's paintComponent() needs to overridden, so that it can copy the image in Image buffer and paint that on the graphics context.
Now comes the real trick. The loop which calls repaint() must do some arithmetic to make sure it does not go beyond drawing 60 times, i.e. looping 60 times, per second. If and when it does then it must call Thread.sleep(sleepTime), where sleepTime is the number of milliseconds left in a second after looping 60 times. It might happen sometime that your loop may take more than a second to complete 60 iterations, then don't just go ahead for next iteration, but call Thread.yield(). This will give other threads a chance to use the CPU, e.g. maybe your EDT. To make the matter more complicated, do not keep yielding always, so might want to put some logic to make sure that yield for only x consecutive times. This last scenario should be very rare, if at all. This scenario means the system is under heavy load.
Remember, repaint() is thread safe and allowed to be called from any thread. It schedules a paint() call on EDT. So, calling repaint() does not guarantee a paint. So, you may want to experiment with different values of FPS to find the one which suites you.
By the way, the trick of rendering to an in-memory Image is technically called Double buffer. This gives us the ability to render nice smooth animations.
Further reading:-
LANSim - Wrote this code a long time back. You can use this code as an example.
http://java.sun.com/docs/books/performance/1st_edition/html/JPSwingThreads.fm.html
Killer Game Programming in Java - This book is on this subject.
Have you looked at SwingWorker? It's a simple framework that lets you run computations in the background and periodically publish updates to the GUI thread.

Categories

Resources