Java Concurrency/Threads(4) —— synchronized

package com.guoqiang;

import java.util.zip.CheckedOutputStream;

import static com.guoqiang.ThreadColor.*;

public class Main {

    public static void main(String[] args) {
        CountDown cd = new CountDown();

        Thread t1 = new ThreadCountDown(cd);
        t1.setName("Thread 1");
        Thread t2 = new ThreadCountDown(cd);
        t2.setName("Thread 2");

        t1.start();
        t2.start();
    }
}

class CountDown {
    public void countDown() {
        String color;
        switch (Thread.currentThread().getName()) {
            case "Thread 1" :
                color = ANSI_CYAN;
                break;
            case "Thread 2":
                color = ANSI_RED;
                break;
            default:
                color = ANSI_GREEN;
        }
        for (int i = 10; i >= 0; i--) {
            System.out.println(color + Thread.currentThread().getName() + ": i = " + i);
        }
    }
}

class ThreadCountDown extends Thread {
    private CountDown countDown;
    public ThreadCountDown(CountDown cd) {
        countDown = cd;
    }
    @Override
    public void run() {
        countDown.countDown();
    }
}

OUT:

将Class:CountDown改为:

class CountDown {
    private int i; //将i变为全局变量
    public void countDown() {
        String color;
        switch (Thread.currentThread().getName()) {
            case "Thread 1" :
                color = ANSI_CYAN;
                break;
            case "Thread 2":
                color = ANSI_RED;
                break;
            default:
                color = ANSI_GREEN;
        }
        for (i = 10; i >= 0; i--) {
            System.out.println(color + Thread.currentThread().getName() + ": i = " + i);
        }
    }
}

OUT:

原因:

  1. Heap是一个进程的所有threads共享的一段内存空间
  2. 每个threads有自己独立的无法被别人访问的thread stack空间
  3. local variables 局部变量存放在thread stack中,每个threads都有自己独立的local variable的副本(存放线程栈空间)
  4. object instance value 存放在heap上,每个在同一个对象上工作的threads,共享对象的全局变量。

synchronized 关键词

使用synchronized关键词修饰static object / static method
synchronized 一个 语句块
```java
synchronized(this) { // synchronized 的对象必须存在在heap上,多个线程对这个对象共享。
statement1;
statement2;
}

猜你喜欢

转载自www.cnblogs.com/isguoqiang/p/11469162.html