+ -
当前位置:首页 → 问答吧 → 求各位大虾帮忙解决线程问题!!!

求各位大虾帮忙解决线程问题!!!

时间:2011-10-13

来源:互联网

public class Demo5 {
public static void main(String[] args) {
     D5 d1 = new D5();
     D5 d2 = new D5();
     D5 d3 = new D5();
     d1.start();
     d2.start();
     d3.start();
   }}

class D5 extends Thread {
private static int i=100;
public void run() {
  while(true) {
   synchronized (this) {
    if(i>0) {
     try {Thread.sleep(10);}catch(InterruptedException e){}
     System.out.println("sales :" + i);
     i--;
    }
   }
   
  }
}
}
为什么我用了synchronized关键字锁住了,却还是没有解决同步问题?

作者: 920123164   发布时间: 2011-10-13

synchronized (this) {

你这句有问题,因为this只是表示当前对像实例,你的main方法中生成了3个不同的实例,所以每次lock的对像不一样。因此你可以使用 this.getclass()来lock实例类就可以了。

作者: shamdeng   发布时间: 2011-10-13

热门下载

更多