2015-05-29 81 views
1

我读这个类代码:同步(...)代码块上使用var = Thread.currentThread()

public class MultiThreadedServer implements Runnable { 
    // some more code 
    protected Thread runningThread = null; 

    public void run() { 
     synchronized(this) { 
      this.runningThread = Thread.currentThread(); 
     } 
     // lots of code 
    } 
} 

这是什么意思?线程本身被用作标志来锁定资源?我一点都不明白。

任何人都知道吗?

+0

'// blablahbla' - '//很多blahblahblah'的 - 这是一个不走我的。 'this'指向'MultiThreadedServer'的实例,而不是线程(它具有无效的标识符) –

+3

我喜欢'protected Thread running = null;'的空间;' – Tschallacka

+0

它不使用线程作为锁,它使用Runnable对象。给多个线程的是同一个对象吗? Runnable中是否有其他方法可以同步? –

回答

2

thisRunnable,而不是一个线程,因此在同步线程本身上完成的,你写的。

它可能有点令人困惑,但如果是例如非常可行。该对象由多个并发线程访问。

干杯,

+1

因此它同步Runnable以避免同时访问线程之间共享的run()方法? – Csi

+2

@Csi不是整个'run'方法,只有'synchronized(this)'块 –

1

this.runningThread = Thread.currentThread();只是给你一个链接到当前线程。

这样,您不必一直致电Thread.currentThread(),节省了方法调用开销。

并且,呃,在protected Thread running thread = null;的空间不利于要么...

+0

“runningThread”字段不仅仅是为了方便,我高度怀疑它只用于'run'方法,尤其是因为它被标记为'protected'。 –

+0

啊,runningThread上的拼写错误,抱歉。 – Csi