package sync.method;
class PrintCH {
public static void print(char c) {
for (int i = 0; i < 4; i++) {
System.out.print(c);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class SyncMassExample extends Thread {
public char c;
public /*static*/ PrintCH printCH = new PrintCH(); ///
public SyncMassExample(char c) {
this.c = c;
}
public void run() {
synchronized (printCH) {
PrintCH.print(c);
}
}
public static void main(String[] args) {
SyncMassExample s1 = new SyncMassExample('a');
SyncMassExample s2 = new SyncMassExample('b');
s1.start();
s2.start();
}
}
为什么同步代码块后的对象的应用得是静态的 就是我注释的那里 去掉static关键字 输出内容就乱了 交替输出a b
习惯受伤
相关分类