美文网首页
synchronized的基本规则

synchronized的基本规则

作者: 文萃北 | 来源:发表于2019-05-14 11:08 被阅读0次

来自:http://www.cnblogs.com/skywang12345/p/3479202.html

第一条: 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的该“synchronized方法”或者“synchronized代码块”的访问将被阻塞。

class MyRunable implements Runnable {
    
    @Override
    public void run() {
        synchronized(this) {
            try {  
                for (int i = 0; i < 5; i++) {
                    Thread.sleep(100); // 休眠100ms
                    System.out.println(Thread.currentThread().getName() + " loop " + i);  
                }
            } catch (InterruptedException ie) {  
            }
        }  
    }
}

public class Demo1_1 {

    public static void main(String[] args) {  
        Runnable demo = new MyRunable();     // 新建“Runnable对象”

        Thread t1 = new Thread(demo, "t1");  // 新建“线程t1”, t1是基于demo这个Runnable对象
        Thread t2 = new Thread(demo, "t2");  // 新建“线程t2”, t2是基于demo这个Runnable对象
        t1.start();                          // 启动“线程t1”
        t2.start();                          // 启动“线程t2” 
    } 
}

总结:synchronized 是获取对象的同步锁。 而不是代码块。 重点在于对象上。

相关文章

网友评论

      本文标题:synchronized的基本规则

      本文链接:https://www.haomeiwen.com/subject/jlojaqtx.html