I'm playing around 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 would be something like:
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
So it doesn't seem concurrent but sequential. Is it because of the speed?
Creating the second thread takes more time than the first one needs to finish. Do this:
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.
It's because printing 20 dates is much faster than you think, and the first thread has thus completed its task before the first instruction of the second thread has been executed.
Or it's because the scheduler decided to execute all the instructions of thread 1 before letting thread 2 execute its instructions.
Make each thread do much more things, and you'll start seeing the parallelism. Or make them do the same things, but slower, by adding Thread.sleep()
calls in the loops.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With