synchronized 同步静态方法和方法
使用类对象当作锁令旗 因为
public class TraditionalThread {
public static void main(String[] args) {
new TraditionalThread().init();
}
private void init(){
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output(“redbull”);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.output2("apple");
}
}
}).start();
}
static class Outputer{
void output(String message){
//锁铃器必须是共同的对象 故错误
synchronized (Outputer.class){
for(int i = 0;i<message.length();i++){
Character chart = message.charAt(i);
System.out.print(chart);
}
System.out.println();
}
}
static synchronized void output2(String message){
//锁铃器必须是共同的对象 故错误
for(int i = 0;i<message.length();i++){
Character chart = message.charAt(i);
System.out.print(chart);
}
System.out.println();
}
}
}