`

synchronized(this)与synchronized(class)

 
阅读更多

synchronized(class)很特别,它会让另一个线程在任何需要获取class做为monitor的地方等待.class与this做为不同的监视器可以同时使用,不存在一个线程获取了class,另一个线程就不能获取该class的一切实例.

 

根据下面的代码自行修改,分别验证下面的几种情况:

synchronized(class)
synchronized(this)
->线程各自获取monitor,不会有等待.
synchronized(this)
synchronized(this)
->如果不同线程监视同一个实例对象,就会等待,如果不同的实例,不会等待.
synchronized(class)
synchronized(class)
->如果不同线程监视同一个实例或者不同的实例对象,都会等待.

package thread.sync;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RunnableTest implements Runnable {

    private static boolean flag = true;

//    private static synchronized void testSyncMethod() { // 注意static修改的同步方法,监视器=class
//        for (int i = 0; i < 100; i++) {
//            System.out.println("testSyncMethod:" + i);
//        }
//    }

    private void testSyncMethod() { 
        synchronized (this) {
            for (int i = 0; i < 100; i++) {
                System.out.println("testSyncMethod:" + i);
            }
        }
    }

    private void testSyncBlock() {

        synchronized (this) { // 注意this做为监视器.它与class分别是二个不同监视器.不会存在class被获取,this就要等的现象.这也是我以前关于监视器的一个误区.
            for (int i = 0; i < 100; i++) {
                System.out.println("testSyncBlock:" + i);
            }
        }

        // synchronized (RunnableTest.class) { // 显示使用获取class做为监视器.它与static synchronized method隐式获取class监视器一样.
        // for (int i = 0; i < 100; i++) {
        // System.out.println("testSyncBlock:" + i);
        // }
        // }
    }

    public void run() {

        // flag是static的变量.所以,不同的线程会执行不同的方法,只有这样才能看到不同的锁定效果.
        if (flag) {
            flag = false;
            testSyncMethod();
        } else {
            flag = true;
            testSyncBlock();
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(2);
        RunnableTest rt = new RunnableTest();
        RunnableTest rt1 = new RunnableTest();
        exec.execute(rt);
        exec.execute(rt1);
        exec.shutdown();
    }
}

 

分享到:
评论

相关推荐

    深析Synchronized关键字(小白慎入,深入jvm源码,两万字长文)

    目录一、synchronized基础1.1synchronized的使用1.1示例1.2验证1.2.1 普通方法和代码块中使用this是同一个监视器(锁),即某个具体调用该代码的对象1.2.2 静态方法和代码块中使用该类的class对象是同一个监视器,...

    PHP pthreads v3下同步处理synchronized用法示例

    本文实例讲述了PHP pthreads v3下同步处理synchronized用法。分享给大家供大家参考,具体如下: ...class Count extends Thread { public $cnt = 0; public function run() { $this-&gt;add(); } public funct

    SynchorizedDemo

    synchronized(this)与synchronized(class) 简单实例 分类: Android Java

    oa源码 大型oa asp.net 源码

    public partial class login2 : Page { [AccessedThroughProperty("chpwd")] private ImageButton _chpwd; [AccessedThroughProperty("dropBranch")] private DropDownList _dropBranch; ...

    java聊天室源程序

    public class BroadCast extends Thread { ClientThread clientthread; ServerThread serverthread; String str; public BroadCast(ServerThread serverthread) { this.serverthread = serverthread; } ...

    Java学习题答案

    (15分) 主要相同点: Lock能完成synchronized所实现的所有功能.(其它不重要) 主要不同点: Lock有比synchronized更精确的线程语义和更好的性能(在相同点中回答此点也行) synchronized会自动释放锁....

    android的 AIDL 例子

    public class IPersonImpl extends IPerson.Stub{ // ������������ private int age; private String name; @Override // ��ʾname��age public String display() throws RemoteException { ...

    Java自定义异常案例--ExceptionManager(java源码)

    * This class &lt;code&gt;ExceptionManager&lt;/code&gt; and its subclasses are a form of * &lt;code&gt;Exception&lt;/code&gt;. It is used to wrap all the &lt;code&gt;Throwable&lt;/code&gt; instances * and handle them in a unified way...

    java课程设计

    synchronized (this){ if(isplay) chosenClip.play(); else { try{this.wait();} catch(InterruptedException e){e.printStackTrace();} }//else try { this.wait(); } catch (InterruptedException e) ...

    j2me手机蓝牙OBEX传文件代码

    synchronized(this){ this.notify(); } } public void servicesDiscovered( int transID, ServiceRecord[] servRecord ) {} public void serviceSearchCompleted( int transID, int respCode ) {} } 7.服务查询...

    SVGPathView

    /** * PathView is an View that animate ... * or resided it must be synchronized with this object. */ private final Object mSvgLock = new Object(); /** * Thread for working with the object above.

    用Java语言开发的网络蚂蚁,很实用哦

    public class DownLoad{ URL url; String objFile; long nStartPos; RandomAccessFile rf; public DownLoad(String objFile,long nStartPos) throws IOException{ this.nStartPos=nStartPos; this.objFile=...

    缓存穿透.txt

    synchronized (this){ allUserCount= (Long) redisTemplate.opsForValue().get(Constants.ALL_USER_COUNT); if(allUserCount==null){ allUserCount=userMapper.selectAllUserCount(); redisTemplate....

    Java 2实用教程(第三版)实验指导与习题解答

    Java 2实用教程(第三版)实验指导与习题解答 清华大学出版社 (编著 耿祥义 张跃平) 实验模版代码 建议使用文档结构图 (选择Word菜单→视图→文档结构图) 上机实践1 初识Java 4 实验1 一个简单的应用程序 ...

    JAVA实现SOCKET聊天

    public class ChatHandler implements Runnable { protected Socket socket; protected ObjectInputStream dataIn; protected ObjectOutputStream dataOut; protected Thread listener; protected static ...

    [工具软件] Netkit Package for .NET 5.0.6132

    A set of .NET classes that makes the work of querying DNS servers for resource record types defined by RFC-1034 and RFC-1035, and performing domain registration with the WhoIs class more easily....

    Java 数据库主键生成类 IdWorker

    public synchronized long nextId() { long timestamp = this.timeGen(); if (this.lastTimestamp == timestamp) { this.sequence = (this.sequence + 1) & this.sequenceMask; if (this.sequence == 0) { System....

    java—多线程的通信、生产者与消费者模式

    run方法是不能用synchronized修饰,他是继承来的,不能改变其结构,而且,如果run方法加了synchronized,就变成单线程了,就没有并发了。 只要不是静态的同步方法,同步方法默认的同步监视器就是this。 静态的同步...

    线程间通信

    public synchronized void put(String name,String sex){ this.name=name; try{ Thread.sleep(10); }catch(Exception e){ System.out.println(e.getMessage()); } this....

    JAVA中的关键字和保留字

    class - 4 - continue - 5 - default - 5 - do - 6 - double - 6 - else - 6 - extends - 6 - false - 7 - final - 7 - finally - 7 - float - 8 - for - 8 - if - 8 - implements - 9 - import - 9 - instanceof - ...

Global site tag (gtag.js) - Google Analytics