public class Main {
public static void main(String[] args) {
SynDemo d = new SynDemo();
Thread1 th1 = new Thread1(d);
Thread2 th2 = new Thread2(d);
th1.start();
th2.start();
}
}
class SynDemo {
// synchronized
synchronized void printNumber(String string) {
for (int i = 0; i < 2000; i++) {
// Log.i("" + string, String.valueOf(i));
System.out.println(string + " = " + String.valueOf(i));
}
}
}
class Thread1 extends Thread {
private SynDemo d;
public Thread1(SynDemo sDemo) {
d = sDemo;
}
@Override
public void run() {
super.run();
d.printNumber("Thread1");
}
}
class Thread2 extends Thread {
private SynDemo d;
public Thread2(SynDemo sDemo) {
d = sDemo;
}
@Override
public void run() {
super.run();
d.printNumber("T2");
}
}
output:
without synchronizedThread1 = 0
Thread1 = 1
Thread1 = 2
T2 = 0
T2 = 1
T2 = 2
T2 = 3
T2 = 4
T2 = 5
T2 = 6
Thread1 = 3
Thread1 = 4
Thread1 = 5
with synchronized
Thread1 = 0
Thread1 = 1
Thread1 = 2
Thread1 = 3
Thread1 = 4
Thread1 = 5
T2 = 0
T2 = 1
T2 = 2
T2 = 3
T2 = 4
T2 = 5
No comments:
Post a Comment