/**
* Created by Vincent on 2014/7/22.
*/
public class TraditionalThreadSychronized {
public static void main(String[] args) {
new TraditionalThreadSychronized().init();
}
private void init() {
final OutPut outPut = new OutPut();
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outPut.output("tianlongbabu");
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
outPut.output("shediaoyingxiongzhuan");
}
}
}.start();
}
class OutPut {
public void output(String name) {
int len = name.length();
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
output方法写法跟平时大家用的工具类方法一样,为什么会有线程不安全问题呢?如果方法如下写:
class OutPut {
private String xxx="";
public void output(String name) {
int len = name.length();
synchronized (xxx){
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
package com.thread.sychronized; /** * Created by Vincent on 2014/7/22. */ public class TraditionalThreadSychronized { public static void main(String[] args) { new TraditionalThreadSychronized().init(); } private void init() { final OutPut outPut = ne