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
  • 相关阅读:
    foj 2111 Problem 2111 Min Number
    hdoj 1175 连连看
    poj 2377 Bad Cowtractors
    poj 3666 Making the Grade
    2018华南理工大学程序设计竞赛 H-对称与反对称
    hdoj 4293 Groups
    FOJ Problem 2273 Triangles
    poj 3411 Paid Roads
    Codeforces 235A. LCM Challenge
    离散对数二连 poj 2417 Discrete Logging & HDU 2815 Mod Tree
  • 原文地址:https://www.cnblogs.com/brant/p/6028553.html
Copyright © 2011-2022 走看看