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

【转】线程八锁

时间:2017-02-19 23:50:49      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:out   this   test   ide   dmi   string   ace   tor   tac   

package com.java.juc;
/**
 * 题目:判断打印 "one" or "two"
 * 
 * 1.两个普通同步方法,两个线程 ,标准打印,打印?// one two
 * 2.新增Thread.sleep(3000) 给getOne() 打印? // 3s 后打印 one two
 * 3.新增普通方法 getThreee 打印?// 先打印three 三秒后打印 one two
 * 4.两个普通同步方法,两个number对象,打印? // two 3s后打印 one
 * 5.修改getOne()为静态同步方法,一个number对象,打印?     // two 3s后打印 one
 * 6.修改两个方法均为静态同步方法,一个number对象,打印?// 3s 后打印 one two
 * 7.修改getOne()为静态同步方法,getTwo()为非静态同步方法 ,两个number,一个调用one,一个调用two //two 3s后打印 one
 * 8.两个都改为静态同步方法,两个number 一个调用getOne(),一个调用getTwo() //3s 后打印 one two
 * @author Administrator
 *
 */
public class TestThread8Monitor {

    public static void main(String[] args) {

        final Number number = new Number();
        final Number number2 = new Number();
        new Thread(new Runnable(){
            @Override
            public void run() {
                number.getOne();
            }
        }).start();
        new Thread(new Runnable(){
            @Override
            public void run() {
                number2.getTwo();
            }
        }).start();
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                number.getThree();
            }
        }).start();*/
    }

}

class Number{
    
    public static synchronized void getOne(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("one");
    }
    
    public static synchronized void getTwo(){
        System.out.println("two");
    }
    
    public void getThree(){
        System.out.println("three");
    }
}

某一时刻只有一个对象持有锁,不管有多少个方法,其他线程都无法持有锁

 

线程八锁的关键:

  1.非静态方法的锁默认为this,静态方法的锁为对应的Class 实例(类的字节码)。

  2.某一时刻内,只能有一个线程持有锁,无论几个方法。

 转载自:http://www.cnblogs.com/wq3435/p/6366913.html

【转】线程八锁

标签:out   this   test   ide   dmi   string   ace   tor   tac   

原文地址:http://www.cnblogs.com/ccfdod/p/6417736.html

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