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