zoukankan      html  css  js  c++  java
  • 多线程篇八:线程锁

    1.线程锁Lock/ReentrantLock

    package com.test.lock;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    //线程锁,通常用于替换synchronized,比synchronized更加面向对象
    public class LockTest {
        static class Outputer{
            Lock locks=new ReentrantLock();
            //方法1
            public void output1(String name){
                int len=name.length();
                locks.lock();//确保完整输出chenxiaobing后再输出donyanxia
                try{
                    for(int i=0;i<len;i++){
                        System.out.print(name.charAt(i));
                    }
                    System.out.println();
                }finally{
                    locks.unlock();//避免执行的代码发送异常,导致死锁,因此需要使用finally,无论执行是否成功,都进行解锁
                }
            }
        }
        public void init(){
            final Outputer o=new Outputer();
            
            //线程1
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        o.output1("chenxiaobing");
                    }
                }
            }).start();
            
            //线程2
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        o.output1("donyanxia");
                    }
                }
            }).start();
        }
        public static void main(String[] args) {
            new LockTest().init();
            //交替输出chenxiaobing、donyanxia
        }
    }
    View Code
  • 相关阅读:
    Wordpress安装及4.6漏洞问题
    天朝挖煤的题已经不会做了。。
    Python str decode---error
    requests库的初级学习
    Python虚拟环境的搭建
    天朝挖煤CTF
    七、TCP粘包和拆包
    六、Netty的Handler
    五、GoogleProtobuf
    三、Netty高性能架构设计
  • 原文地址:https://www.cnblogs.com/brant/p/6028553.html
Copyright © 2011-2022 走看看