Skip to content

Instantly share code, notes, and snippets.

@ge0ffrey
Created September 1, 2016 15:34
Show Gist options
  • Select an option

  • Save ge0ffrey/1b6c0b061745b73f8a5282d4c05a47d4 to your computer and use it in GitHub Desktop.

Select an option

Save ge0ffrey/1b6c0b061745b73f8a5282d4c05a47d4 to your computer and use it in GitHub Desktop.
public class TwMain {
// I have 8 cores.
// If I set this to 2, then my CPU is at 25%
// If I set this to 4, then my CPU is at 50%
// If I set this to 6, then my CPU is at 74%
// If I set this to 8, then my CPU is at 98%
// If I set this to 10, then my CPU is at 98%
private static final int ACTIVE_THREAD_LIMIT = 10;
private final static Semaphore SEMAPHORE = new Semaphore(ACTIVE_THREAD_LIMIT, true);
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
StringBuilder name = new StringBuilder();
for (int j = 0; j < i + 1; j++) {
name.append(i);
}
Thread thread = new Thread(new Runner(name.toString()));
thread.start();
}
}
public static class Runner implements Runnable {
private final String name;
private long count = 0;
public Runner(String name) {
this.name = name;
}
@Override
public void run() {
long start = System.currentTimeMillis();
while (count < 3000) {
if (count % 100 == 0) {
if (count != 0) {
SEMAPHORE.release();
}
try {
SEMAPHORE.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
System.out.println((System.currentTimeMillis() % 100000) + " - " + name + " = " + count);
}
drainCpu(10);
count++;
}
System.out.println((System.currentTimeMillis() % 10000) + " - " + name + " finished in " + (System.currentTimeMillis() - start));
}
public void drainCpu(long millis) {
long end = System.currentTimeMillis() + millis;
long l = 0;
while (System.currentTimeMillis() < end) {
l = l + 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment