import java.util.Random;public class Test0_5 {
// 一个标志值
private static Object object = new Object(); //用来测试synchronized private static int flag = 1; public static void main(String[] args) { new Thread("Thread-01") { public void run() {
new Test0_5().operate();
} }.start(); // 启动第一个线程 new Thread("Thread-02") { public void run() { new Test0_5().operate(); } }.start(); // 启动第二个线程 } public void operate() {
synchronized (this){ // 方法一...........不能起到同步的效果 //synchronized (Test0_5.class) { //方法二............同样不能
//synchronized (object){ //方法三............同样不能 flag++; try { // 增加随机性,让不同线程能在此交替执行 Thread.sleep(new Random().nextInt(5)); } catch (InterruptedException e) { e.printStackTrace(); } flag--;
} System.out.println("Thread: " + Thread.currentThread().getName() + " /Current flag: " + flag); }}
/*方法二和方法三应该是对的 ,但输出结果中任然看到
Thread: Thread-01 /Current flag: 2
Thread: Thread-02 /Current flag: 1
这种结果*/
// 一个标志值
private static Object object = new Object(); //用来测试synchronized private static int flag = 1; public static void main(String[] args) { new Thread("Thread-01") { public void run() {
new Test0_5().operate();
} }.start(); // 启动第一个线程 new Thread("Thread-02") { public void run() { new Test0_5().operate(); } }.start(); // 启动第二个线程 } public void operate() {
synchronized (this){ // 方法一...........不能起到同步的效果 //synchronized (Test0_5.class) { //方法二............同样不能
//synchronized (object){ //方法三............同样不能 flag++; try { // 增加随机性,让不同线程能在此交替执行 Thread.sleep(new Random().nextInt(5)); } catch (InterruptedException e) { e.printStackTrace(); } flag--;
} System.out.println("Thread: " + Thread.currentThread().getName() + " /Current flag: " + flag); }}
/*方法二和方法三应该是对的 ,但输出结果中任然看到
Thread: Thread-01 /Current flag: 2
Thread: Thread-02 /Current flag: 1
这种结果*/
Thread: Thread-01 /Current flag: 1
Thread: Thread-02 /Current flag: 1
System.out.println("Thread: " + Thread.currentThread().getName()+ " /Current flag: " + flag);放在同不块中,所以打印没有同步