线程同步机制

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

   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();
}

原文地址:https://www.cnblogs.com/dsking/p/5254099.html