Java并行编程

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决定,因此该方法只是一个建议。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值