zoukankan      html  css  js  c++  java
  • 传统的线程互斥技术: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 的话,运行结果如图。

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

     

  • 相关阅读:
    如何在谷歌浏览器增加插件
    电脑更换硬盘
    电脑增加内存条
    了解计算机存储器
    Vue ----------- 了解, 展示json 数据
    JSON -------- json与字符串之间的转换
    JSON ------ 创建与访问
    Chartjs 简单使用 ------ 制作sin cos 折线图
    WebStorm ------------ 调整字体大小和背景
    输出正整数的各位数字
  • 原文地址:https://www.cnblogs.com/2YSP/p/7696162.html
Copyright © 2011-2022 走看看