In parallel or in series?

I play with Threads in Java.
The following example I found on a website:

public class ThreadTest { public static void main(String args[]) { Thread t1 = new Thread(new Thread1()); t1.start(); Thread t2 = new Thread(new Thread2()); t2.start(); } } public class Thread1 implements Runnable { @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(new java.util.Date()); } } } public class Thread2 implements Runnable { @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(i); } } } 

The expected result will be something like this:

 Mon Nov 11 20:06:12 CET 2013 0 1 2 3 4 5 6 7 8 9 Mon Nov 11 20:06:12 CET 2013 10 

But I get:

 0 1 2 3 ... 19 Mon Nov 11 20:06:12 CET 2013 Mon Nov 11 20:06:12 CET 2013 Mon Nov 11 20:06:12 CET 2013 ... Mon Nov 11 20:06:12 CET 2013 

Thus, it does not seem parallel, but consistent. Is it because of speed?

+6
source share
2 answers

Creating a second thread takes longer than it takes to complete the first. Do it:

 public class ThreadTest { public static void main(String args[]) { Thread t1 = new Thread(new Thread1()); Thread t2 = new Thread(new Thread2()); t1.start(); t2.start(); } } public class Thread1 implements Runnable { @Override public void run() { for (int i = 0; i < 200000; i++) { System.out.println(new java.util.Date()); } } } public class Thread2 implements Runnable { @Override public void run() { for (int i = 0; i < 200000; i++) { System.out.println(i); } } } 

If in doubt, use Integer.MAX_VALUE instead of 200000.

+3
source

This is because printing 20 dates is much faster than you think, and the first thread completed its task before the first command of the second thread was executed.

Or is it because the scheduler decided to execute all instructions of thread 1 before allowing thread 2 to execute its instructions.

Make each thread a lot bigger and you will begin to see parallelism. Or get them to do the same, but slower by adding Thread.sleep() calls to loops.

+2
source

Source: https://habr.com/ru/post/957858/


All Articles