..because the other Thread is sleeping. That the chance for the opposite Thread to run.
http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html[
^]
It's better visible like this:
package com.cp;
public class ThreadApply {
public int iCount=0;
public ThreadApply(){
Thread1 t1 = new Thread1("thread 1");
Thread2 t2 = new Thread2("thread 2");
}
public static void main(String... args) {
new ThreadApply();
}
private class Thread1 extends Thread {
Thread1(String s) {
super(s);
start();
}
public synchronized void run() {
for (int i = 0; i < 200; i++) {
iCount++;
System.out.println(Thread.currentThread().getName() + " iCount:" + iCount);
try {
} catch (Exception e) {
}
}
}
}
private class Thread2 extends Thread {
Thread2(String s) {
super(s);
start();
}
public void run() {
sum();
}
public synchronized void sum() {
for (int i = 0; i < 20; i++) {
iCount--;
System.out.println("\t" + Thread.currentThread().getName() + " iCount:" + iCount);
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}
}
Thread1
is running at high speed -
Thread2
is waiting until
Thread1
has releases the lock on the referenced value
iCount
.