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
緣由:線程
使用synchronized關鍵詞修飾static object / static method
synchronized 一個 語句塊
```java
synchronized(this) { // synchronized 的對象必須存在在heap上,多個線程對這個對象共享。
statement1;
statement2;
}3d