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();
}
}
package com.guoqiang;
import java.util.zip.Checked