I am trying to write a program that in the Main class can initiate an unknown number of new threads. Each thread, in turn, must call the Singleton Copier class, which must trigger the file transfer action.
My goal, regardless of the number of thread requests, is to limit the number of simultaneous transfers in 2 transfers, so I decided to solve it with Semaphore . My problem is that threads work one by one, and not in parallel.
Here is what I tried to do:
public class Copier { private static final int POOL_SIZE = 2; private static volatile Copier instance = null; private static Semaphore semaphore; private Copier() { } public static Copier getInstance() { if (instance == null) { synchronized (Copier.class) { if (instance == null) { instance = new Copier(); semaphore = new Semaphore(POOL_SIZE); } } } return instance; } public void fileTransfer(CopyThread copyThread) { try { semaphore.acquire(); System.out.println("Running thread..."); copyThread.run(); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); System.out.println("Thread released.."); } } }
This is my Main class:
public class Driver { public static void main(String[] args) { Copier copier = Copier.getInstance(); CopyThread copyThread1 = new CopyThread(); CopyThread copyThread2 = new CopyThread(); copier.fileTransfer(copyThread1); copier.fileTransfer(copyThread2); } }
At startup - you can see by the output streams running one after the other, while my goal is to have up to two simultaneous streams. What have I done wrong?
Running thread... 3.998784MB were transferred in 5.902514932 seconds Thread released.. Running thread... 4.062673MB were transferred in 7.199550077 seconds Thread released..
source share