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

  • 相关阅读:
    Android属性动画
    android 保存配置文档
    android 不自动弹出虚拟键盘
    android 常用代码
    android imageswitcher gallery 根据数据库内图片名字进行查看/删除
    android 文件内容和 textview 操作
    用 java 语言获取 1N 的不重复随机数
    android 数据库 备份还原
    解决Ubuntu 输入法不显示
    android 添加文本内容到sqlite表中
  • 原文地址:https://www.cnblogs.com/ctaixw/p/7979762.html
Copyright © 2020-2023  润新知