Java Queue-Based Multithreading API
A simple queue-based multithreading api that can be used to
Importing
Maven
Repository
<repository>
<id>Java-Queue-Multithread-repo</id>
<url>https://github.com/HyperCodec/Java-Queue-Multithread/raw/mvn-repo/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
Dependency
<dependency>
<groupId>me.hypercodec</groupId>
<artifactId>java-queue-multithread</artifactId>
<version>1.0</version> <!-- replace with latest release version (Intellij should prompt you) -->
</dependency>
Gradle
Repository
repositories: {
maven {
url "https://github.com/HyperCodec/Java-Queue-Multithread/raw/mvn-repo/"
}
// ...
}
Dependency
dependencies: {
implementation("me.hypercodec:java-queue-multithread:1.0") // replace with latest release version (Intellij should prompt you)
// ...
}
How to Use
Initialization
Run ThreadManager.init(amount of threads)
in the beginning of your code (such as the main() function). This gets everything set up for
Creating Tasks
A Task object is similar to a Runnable, but you use start() rather than run().
Extending Via Separate Class
You can extend the class by doing this:
Example Class
public class ExampleTask extends Task {
@Override
protected void start() {
// code here
}
}
Extending Via Instantiation
If you don't need an entire class for it, you can just do it like this:
Example Instantiation
Task task = new Task() {
@Override
protected void start() {
// code here
}
};
Starting Tasks
A task can be started by simply doing ThreadManager.startTask(task)
or ThreadManager.startTasks(collection of tasks)
as shown below:
Task Starting Examples
// Somewhere during startup
ThreadManager.init();
// --------------------------------
// Using ExampleTask from earlier and startTask()
Task task = new ExampleTask();
ThreadManager.startTask(task);
// --------------------------------
// Using the other method of Task extension and a List of Tasks
List<Task> tasks = new ArrayList<>();
for(int i = 0; i < 1000; i++) {
int finalI = i;
tasks.add(new Task() {
@Override
protected void start() {
for(int i2 = 0; i2 < 100; i2++) {
System.out.printf("%s from task %s in thread %s%n", i2, finalI, this.parent.getName());
}
}
});
}
ThreadManager.startTasks(tasks);
If recursively adding the same task for some reason, use task.clone() when adding or else it will error.