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:

The Class: CountDown read:

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:

the reason:

  1. Heap is shared by all threads for some memory space of a process
  2. Each thread stack space threads have their own independent and can not be accessed by others
  3. local variables Local variables stored in the thread stack, each has its own separate threads a copy of the local variable (thread stack storage space)
  4. object instance value stored on the heap, threads of each job on the same object, shared global variable objects.

synchronized keyword

Object keyword synchronized using a modified static / static Method
synchronized statement block a
`` `Java
synchronized (the this) {// synchronized object must be present on the heap, object shared by multiple threads.
statement1;
statement2 is;
}

Guess you like

Origin www.cnblogs.com/isguoqiang/p/11469162.html