I have a quad core processor. I create 4 threads and run an intensive cpu loop, and it takes> 4 times longer than running all the procedures in one thread.
I created two projects for comparison: one with a stream and one without it. I will show the code and runtime. Just notice that a project without streaming processing looks weird, I would like to replicate the memory overhead because I was not sure how much this would affect the runtime. So, here is the code without slicing:
class TimeTest implements Runnable { private Thread t; private String name; TimeTest(String name) { this.name = name; System.out.println("Creating class " + name); } public void run() { System.out.println("Running class " + name); int value = 100000000;
This takes about 11 seconds to complete.
Here is the code with threading:
class RunnableTest implements Runnable { private Thread t; private String name; RunnableTest(String name) { this.name = name; System.out.println("Creating thread " + name); } public void run() { System.out.println("Running thread " + name); int value = 100000000;
This takes about 1 minute 13 seconds.
Now, in the example I'm studying, they call Thread.sleep at runtime for 50 ms. If I do this, threads will be faster if I also call Thread.sleep (50) in a non-threaded class.
This is great, I know how to make it work. But the reason I study this is because I am doing pathfinding, and I am not going to add a sleep call to something that already takes a lot of time, and I donβt need to stop and do nothing even in 1 ms (if only it will not be absolutely necessary).
So, what am I interested in, what am I missing? Do the threads really need to be euthanized or should the object wait for them to work as I expect (i.e., all four loops in parallel)?
Even if I'm just wrong, why does it take so much longer? I think the worst case scenario, it will still work after 11 seconds, it just ends in some kind of unexpected order ....