0

基本上我的层次结构是我有一个 A 类,它启动 B 类的 100 个线程,B 类使用一个名为FileCreator. FileCreator类有一个称为writeToFile()同步的方法。这就是我在 B 类中实例化它的方式:

FileCreator newFile = new FileCreator(downloadFolder, content, page.getWebURL());
newFile.writeToFile();

现在我的问题是writeToFile()实际上并没有同步。基本上这就是我对我所做的writeToFile()

public synchronized void writeToFile() {
        System.out.println("Thread accessed");
        //Some stuff here
        System.out.println("Thread FINISHED!");
}

但是我在控制台中得到了这个结果:

Thread accessed
Thread accessed
Thread FINISHED!
Thread FINISHED!

所以它并没有真正同步。因为这些类是由不同的线程访问的,所以我假设这会导致问题。有没有办法真正同步我的方法,以便一次只有一次访问?

4

2 回答 2

1

它在每个实例的基础上同步。synchronized在实例方法上意味着

synchronized(this) {
    ...
}

但是由于您有 100 个实例,因此它们都不会阻塞。您需要在共享对象上进行同步。将一个lock对象传递给每个实例,或者只创建一个传递给每个实例的实例Threadsynchronize在那个实例上。

于 2013-10-12T14:08:11.957 回答
1

我会使用“虚拟”对象并对其进行同步。块级别更有效,因为它不会锁定整个方法。

Object xLock = new Object(); // !!! in you main thread

....

public void writeToFile() {
    synchronized(xLock ){
      System.out.println("Thread accessed");
      //Some stuff here
      System.out.println("Thread FINISHED!");
    }       
}

但当然你也可以写:

 public void writeToFile() {
    synchronized(this){
      System.out.println("Thread accessed");
      //Some stuff here
      System.out.println("Thread FINISHED!");
    }       
  }

}

请记住,xLock应该在主线程中启动。

作为参考

=======================

方法级别

class MethodLevel {

  //shared among threads
SharedResource x, y ;

public void synchronized method1() {
   //multiple threads can't access
}
public void synchronized method2() {
  //multiple threads can't access
}

 public void method3() {
  //not synchronized
  //multiple threads can access
 }
}

块级

class BlockLevel {
  //shared among threads
  SharedResource x, y ;

  //dummy objects for locking
  Object xLock = new Object();
  Object yLock = new Object();

    public void method1() {
     synchronized(xLock){
    //access x here. thread safe
    }

    //do something here but don't use SharedResource x, y
    // because will not be thread-safe
     synchronized(xLock) {
       synchronized(yLock) {
      //access x,y here. thread safe
      }
     }

     //do something here but don't use SharedResource x, y
     //because will not be thread-safe
    }//end of method1
 }
于 2013-10-12T14:08:45.727 回答