Use ReentrantLock : ReentrantLock « JDK 7 « Java






Use ReentrantLock


import java.io.FileOutputStream;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test {

  public static void main(String[] args) throws Exception {
    Lock myLock = new ReentrantLock();
    Random random = new Random();

    myLock.lock();
    int number = random.nextInt(5);
    int result = 100 / number;
    System.out.println("A result is " + result);
    FileOutputStream file = new FileOutputStream("file.out");
    file.write(result);
    file.close();
  }
}

 








Related examples in the same category

1.Use ReentrantLock to coordinate
2.LinkedBlockingQueue and ThreadPoolExecutor
3.Two ReentrantLock