1 package net.sourceforge.simplegamenet.framework.transport;
2
3 import java.lang.reflect.InvocationTargetException;
4 import java.util.LinkedList;
5 import javax.swing.*;
6
7 public class TaskQueue implements Runnable {
8
9 private LinkedList taskList = new LinkedList();
10 private boolean active = true;
11 private Thread queueThread = new Thread(this,
12 "net.sourceforge.simplegamenet.framework.transport.TaskQueue thread");
13
14 private boolean dispatchToEventThread;
15
16 public TaskQueue(boolean dispatchToEventThread) {
17 this.dispatchToEventThread = dispatchToEventThread;
18 }
19
20 public void start() {
21 queueThread.start();
22 }
23
24 public void run() {
25 Runnable task = null;
26 while (true) {
27 synchronized (this) {
28 while (taskList.size() <= 0 && active) {
29 try {
30 wait();
31 } catch (InterruptedException e) {
32
33 }
34 }
35 if (!active) {
36 return;
37 }
38 task = (Runnable) taskList.removeFirst();
39 }
40 if (dispatchToEventThread) {
41 try {
42 SwingUtilities.invokeAndWait(task);
43 } catch (InterruptedException e) {
44 Throwable throwable = e.getCause();
45 if (throwable != null) {
46 throwable.printStackTrace();
47 }
48 } catch (InvocationTargetException e) {
49 Throwable throwable = e.getCause();
50 if (throwable != null) {
51 throwable.printStackTrace();
52 }
53 }
54 } else {
55 try {
56 task.run();
57 } catch (Throwable throwable) {
58 if (throwable != null) {
59 throwable.printStackTrace();
60 }
61 }
62 }
63 }
64 }
65
66 public synchronized void addTask(Runnable task) {
67 if (active) {
68 taskList.addLast(task);
69 notify();
70 }
71 }
72
73 public synchronized void close() {
74 active = false;
75 notify();
76 }
77
78 }