1.不使用synchronized 关键字代码
package Synch;
public class ClassA {
private int i = 0;
private int a, b;
public void reader() {
System.out.println("this is method reader start " + i);
System.out.println("a= " + a);
System.out.println("b= " + b);
if(a!=b){
System.err.println("synchronized failed");
System.exit(0);
}
System.out.println("this is method reader end " + i);
}
public void writer() {
i++;
System.out.println("this is method writer start " + i);
a++;
b++;
System.out.println("this is method writer end " + i);
}
public static void main(String[] args) {
final ClassA A = new ClassA();
Thread ts = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
A.reader();
}
}
});
Thread ts2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
A.writer();
}
}
});
ts.start();
ts2.start();
}
}
2. 使用synchronized 代码
package Synch;
public class ClassO {
private int i = 0;
private int a, b;
synchronized public void reader() {
System.out.println("this is method reader start " + i);
System.out.println("a= " + a);
System.out.println("b= " + b);
if(a!=b){
System.err.println("synchronized failed");
System.exit(0);
}
System.out.println("this is method reader end " + i);
}
synchronized public void writer() {
i++;
System.out.println("this is method writer start " + i);
a++;
b++;
System.out.println("this is method writer end " + i);
}
public static void main(String[] args) {
final ClassO O = new ClassO();
Thread ts = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
O.reader();
}
}
});
Thread ts2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
O.writer();
}
}
});
ts.start();
ts2.start();
}
}
3.synchronized 关键字是为对象加锁