-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask.java
More file actions
58 lines (46 loc) · 1.66 KB
/
Task.java
File metadata and controls
58 lines (46 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.taskscheduler;
import java.util.concurrent.atomic.AtomicLong;
/**
* Represents a unit of work submitted to the thread pool.
* Supports priority levels and tracks submission time for stats.
*/
public class Task implements Comparable<Task> {
public enum Priority {
LOW(1), MEDIUM(2), HIGH(3);
private final int level;
Priority(int level) { this.level = level; }
public int getLevel() { return level; }
}
private static final AtomicLong ID_COUNTER = new AtomicLong(0);
private final long id;
private final String name;
private final Runnable runnable;
private final Priority priority;
private final long submittedAt;
public Task(String name, Runnable runnable, Priority priority) {
this.id = ID_COUNTER.incrementAndGet();
this.name = name;
this.runnable = runnable;
this.priority = priority;
this.submittedAt = System.currentTimeMillis();
}
public Task(String name, Runnable runnable) {
this(name, runnable, Priority.MEDIUM);
}
public void execute() {
runnable.run();
}
public long getId() { return id; }
public String getName() { return name; }
public Priority getPriority() { return priority; }
public long getSubmittedAt() { return submittedAt; }
// Higher priority tasks come first in the queue
@Override
public int compareTo(Task other) {
return Integer.compare(other.priority.getLevel(), this.priority.getLevel());
}
@Override
public String toString() {
return String.format("Task[id=%d, name='%s', priority=%s]", id, name, priority);
}
}