Created
December 15, 2022 06:53
-
-
Save oldshensheep/034044093ce9608ee3d02d7629c2bf81 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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