Skip to content

Instantly share code, notes, and snippets.

@oldshensheep
Created December 15, 2022 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oldshensheep/034044093ce9608ee3d02d7629c2bf81 to your computer and use it in GitHub Desktop.
Save oldshensheep/034044093ce9608ee3d02d7629c2bf81 to your computer and use it in GitHub Desktop.
package org.example;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;
class Task {
int id;
String data;
Thread thread;
public Task(int id, String data, Thread thread) {
this.id = id;
this.data = data;
this.thread = thread;
}
@Override
public String toString() {
return "Task{" +
"id=" + id +
", data='" + data + '\'' +
", thread=" + thread +
'}';
}
}
public class Sheep {
public static void main(String[] args) {
var blockingQueue = new ArrayBlockingQueue<Task>(10);
var pool = Executors.newFixedThreadPool(10);
pool.execute(() -> {
while (true) {
try {
Task task = blockingQueue.take();
task.data = task.id + " FINISHED.";
LockSupport.unpark(task.thread);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
for (int i = 0; i < Integer.MAX_VALUE; i++) {
int finalI = i;
pool.execute(() -> {
var task = new Task(finalI, null, Thread.currentThread());
try {
blockingQueue.put(task);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
LockSupport.park();
if (task.data == null) {
System.out.println(task);
System.out.println(task);
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment