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 = 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();
}
output方法写法跟平时大家用的工具类方法一样,为什么会有线程不安全问题呢?如果方法如下写:
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();
}
}
}
这样为什么会是线程安全的?如果第一个例子不是线程安全的,那这个例子中 字符串长度会随时改变 也会不是线程安全的呢
请高手帮忙释疑,在这里谢谢了 |
|