传统的线程互斥技术:Synchronized关键字

多个线程操作同一个方法或变量时常常出现错误,要保证每个线程都正常运行就要通过加锁,每次只有一个能够拿到锁通过。如下:

 1 package cn.sp.thread;
 2 
 3 /**
 4  * Created by 2YSP on 2017/10/19.
 5  */
 6 public class TraditionalThreadSynchronized {
 7 
 8 
 9     public static void main(String[] args) {
10         new TraditionalThreadSynchronized().init();
11     }
12 
13     private void init(){
14         final Outputer outputer = new Outputer();
15         new Thread(() ->{
16             while (true){
17                 try {
18                     Thread.sleep(1000);
19                 } catch (InterruptedException e) {
20                     e.printStackTrace();
21                 }
22                 outputer.outPut("wangxiaoxiao");
23             }
24         }).start();
25 
26         new Thread(() ->{
27             while (true){
28                 try {
29                     Thread.sleep(1000);
30                 } catch (InterruptedException e) {
31                     e.printStackTrace();
32                 }
33                 outputer.outPut("lilianjie");
34             }
35         }).start();
36     }
37 
38     class Outputer{
39         public synchronized void outPut(String name){//synchronized通过加锁使两个线程互斥
40             int len = name.length();
41             for(int i=0;i<len;i++){
42                 System.out.print(name.charAt(i));
43             }
44             //打印出字符串后换行
45             System.out.println();
46         }
47     }
48 }

如果没有synchronized 的话,运行结果如图。

不再是依次打印出名字,该关键字还可以加在代码块里。一般为了性能,我们要减少同步执行的代码数量(可以用同步代码块就不用同步方法);

 

posted @ 2017-10-19 23:16  烟味i  阅读(360)  评论(0编辑  收藏  举报