您的位置:首页 > 其它

线程同步机制

2016-03-08 15:01 495 查看
一.当多个线程访问同一份相同的数据,会出现线程安全问题,也就是第一个线程还没有处理完成,另一个线种也执行这个方法。

synchronized关键字放在方法返回类型之前,或者在synchronized括号里面放同一个对象;通用的方法是放类的字节码。

以下举例说明

class Test{
public static void main(String[] args) {
new Test().init();
}

public void init() {
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(100);
outputer.outPut("dingsi");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(100);
outputer.outPut("huahua");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}

class Outputer{
public void outPut(String name){
int length = name.length();
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
System.out.println();

}
}
}

结果如下:



如果把上面打印的方法改为

public synchronized void outPut(String name){
int length = name.length();
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
或者

public void outPut(String name){

int length = name.length();
synchronized (Test.class) {
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
}
System.out.println();
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: