Even one processor can do βseveral things at onceβ in the free sense, but they are not always parallel. You can run 100 threads to work on one core, and they will receive temporary fragments during which each of them can execute several instructions, thereby creating the impression that they are all executed at the same time.
As I said in another SO post: multithreading on a dual core machine?
The term streams usually encompasses three layers of abstraction:
- User threads are threads launched by applications and displayed by N: M:
- Kernel threads , which are threads controlled by the operating system, displayed by N: M:
- Hardware threads that are actually available physical resources.
Java threads are user threads. The 4 cores in your processor are considered hardware threads. Since N: M mapping by layers, you can see that you can have multiple user threads mapped to fewer hardware threads.
Now, having said that, there are usually two classes of streams, each with its own quirks:
- I / O threads . These threads spend most of their time reading / writing from the stream and are blocked in the meantime (they are not scheduled to be executed until their event occurs). There is light on the processor, and many of them can work simultaneously even on one core.
- Computing threads : These threads execute many cycles and make the most of the processor. As a rule, starting more (2x the number of available cores), such threads will degrade performance because the processor has a limited number of function blocks: ALU, FPU, etc.
The second class of the above threads allows you to see the benefits or run a multi-threaded Java program on your quad-core processor. Here is a simple example of a program that first squares the numbers 1.000.000.000, and then in parallel using a thread pool with 4 threads:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; class ThreadTask implements Runnable { private int total = 0; public ThreadTask(int total) { this.total = total; } @Override public void run() { int value = 0; for(int i = 0; i < total; i++) { value = i * i; } } } public class Test { public static void main(String[] args) throws InterruptedException { int total = 1000000000; long start = System.currentTimeMillis(); long value = 0; for(int i = 0; i < total; i++) { value = i * i; } long stop = System.currentTimeMillis(); System.out.println((stop - start) + " ms"); ExecutorService exec = Executors.newFixedThreadPool(4); start = System.currentTimeMillis(); for(int i = 0; i < 4; i++) { exec.submit(new ThreadTask(total / 4)); } exec.shutdown(); exec.awaitTermination(10, TimeUnit.SECONDS); stop = System.currentTimeMillis(); System.out.println((stop - start) + " ms"); } }
Do not set the total
value if it is running too fast. Now I am working on a netbook with Intel Atom, so it is not very fast.
source share