码迷,mamicode.com
首页 > 编程语言 > 详细

多线程加锁二

时间:2018-01-14 19:35:38      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:rac   catch   run   art   new   ring   system   except   int   

package cn.mutipart.thd;

public class Test02 {
    public static void main(String[] args) {
        MyPainter p = new MyPainter();
        new Thread(){
            public void run() {
                while(true){
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    p.print1();
                }
            };
        }.start();
        
        new Thread(){
            public void run() {
                while(true){
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    p.print2();
                }
            };
        }.start();
    }
}

class MyPainter {
    
    private String lock  = new String("线程锁");

    public void print1(){
        synchronized (lock) {
            System.out.print("[不");
            System.out.print("是");
            System.out.print("广");
            System.out.print("告]");
            System.out.println();
        }
    }

    public void print2(){
        synchronized (lock) {
            System.out.print("[X");
            System.out.print("X");
            System.out.print("X");
            System.out.print("X]");
            System.out.println();
        }
    }
}

 

多线程加锁二

标签:rac   catch   run   art   new   ring   system   except   int   

原文地址:https://www.cnblogs.com/yoyo198212/p/8283870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!