class Particle { protected int x; protected int y; protected final Random rng = new Random(); public Particle(int initialX, int initialY) { x = initialX; y = initialY; } public synchronized void move() { x += rng.nextInt(10) - 5; y += rng.nextInt(20) - 10; } public void draw(Graphics g) { int lx, ly; synchronized (this) { lx = x; ly = y; } g.drawRect(lx, ly, 10, 10); } } 看上面一段程序,程序中包含两个sunchronized段。我们知道Java 通过instance of Particle 的锁来进行exclusion控制,这里有一个问题an instance包含几个锁呢?是一个synchronized对应一个 ,还是整个instance就包含一个?进一步考虑,假设现在有两个线程A和B,A要执行move()但是B要执行 draw(),会有什么后果?设当前x=3,y=5...... 通过阅读书籍得知,每一个instance都包含一个锁,所以一旦一个instance进入synchronized区域, 其他synchronized函数或者代码域不能进入,但是非synchronized的代码可以正常执行。 Synchronized instance methods in subclasses employ the same lock as those in their superclasses. But synchronization in an inner class method is independent of its outer class. However, a non-static inner class method can lock its containing class, say OuterClass, via code blocks using: synchronized(OuterClass.this) { /* body */ }.
Thread类的一些静态方法能够应用到当前正在运行的线程当中,这些静态(static)方法 包括: Thread.currentThread() 该方法返回一个当前正在运行线程的一个引用,通过获得的引用可以调用该线程的 一些其他方法。 Thread.interrupted() clears interruption status of the current Thread and returns previous status. (Thus, one Thread's interruption status cannot be cleared from other threads.) Thread.sleep(long msecs) 让当前线程休眠msecs毫秒 Thread.yield() 该方法比较有意思,他会建议JVM去执行其处于等待状态可以执行的线程,但是具体 是不是执行由JVM决定,因此该方法只是一个建议。