zoukankan      html  css  js  c++  java
  • java 多线程 day11 lock


    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    /**
    * Created by chengtao on 17/12/5.
    * Lock 是替代 sycronized 的,相比sycronized 更加面向对象
    * java.util.concurrent.locks.Lock;
    * java.util.concurrent.locks.ReentrantLock;
    */
    public class Thread1101_Lock {

    /**
    * @param args
    */
    public static void main(String[] args)throws Exception {
    new Thread1101_Lock().init();
    }

    private void init() throws Exception{
    final Outputer outputer = new Outputer();
    new Thread(new Runnable(){
    public void run() {
    while(true){
    try {
    Thread.sleep(10);
    } catch (Exception e) {
    e.printStackTrace();
    }
    outputer.output("zhangxiaoxiang");
    }

    }
    }).start();

    new Thread(new Runnable(){
    public void run() {
    while(true){
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    outputer.output("lihuoming");
    }

    }
    }).start();

    }

    static class Outputer{
    Lock lock = new ReentrantLock();
    public void output(String name){
    int len = name.length();
    lock.lock(); //和output1 对比 lock和synchronized的异同
    try{
    for(int i=0;i<len;i++){
    System.out.print(name.charAt(i));
    }
    System.out.println();
    }finally{
    lock.unlock(); //和output1 对比 lock和synchronized的异同
    }
    }

    /*
    通过同步代码块来控制,注意锁对象一定要唯一
    */
    public void output1(String name){
    int len = name.length();
    synchronized (Outputer.class) {
    for(int i=0;i<len;i++){
    System.out.print(name.charAt(i));
    }
    System.out.println();
    }
    }

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

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

  • 相关阅读:
    Django框架基础之序列化
    资产采集
    CMDB
    数据库--三层架构
    Django 项目一补充
    评论楼
    图片预览
    验证码
    如何使用C/C++动态库与静态库中的宏
    Matlab 直线方程、采样函数
  • 原文地址:https://www.cnblogs.com/ctaixw/p/7979762.html
Copyright © 2011-2022 走看看