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:
java

將Class:CountDown改成:ide

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:
this

緣由:線程

  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;
}3d

相關文章
相關標籤/搜索