Worker.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (C) 2004-2022 Artifex Software, Inc.
  2. //
  3. // This file is part of MuPDF.
  4. //
  5. // MuPDF is free software: you can redistribute it and/or modify it under the
  6. // terms of the GNU Affero General Public License as published by the Free
  7. // Software Foundation, either version 3 of the License, or (at your option)
  8. // any later version.
  9. //
  10. // MuPDF is distributed in the hope that it will be useful, but WITHOUT ANY
  11. // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  13. // details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
  17. //
  18. // Alternative licensing terms are available from the licensor.
  19. // For commercial licensing, see <https://www.artifex.com/> or contact
  20. // Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco,
  21. // CA 94129, USA, for further information.
  22. package example;
  23. import java.awt.EventQueue;
  24. import java.util.concurrent.LinkedBlockingQueue;
  25. public class Worker implements Runnable
  26. {
  27. public static class Task implements Runnable {
  28. public void work() {} /* The 'work' method will be executed on the background thread. */
  29. public void run() {} /* The 'run' method will be executed on the UI thread if work() did not throw any exception. */
  30. public void exception(final Throwable t) {} /* The 'exception' method will be executed on the UI thread if work() throws an exception. */
  31. }
  32. protected EventQueue eventQueue;
  33. protected LinkedBlockingQueue<Task> queue;
  34. protected boolean alive;
  35. protected Thread thread;
  36. public Worker(EventQueue eventQueue) {
  37. this.eventQueue = eventQueue;
  38. queue = new LinkedBlockingQueue<Task>();
  39. thread = new Thread(this);
  40. }
  41. public void start() {
  42. alive = true;
  43. thread.start();
  44. }
  45. public void stop() {
  46. alive = false;
  47. thread.interrupt();
  48. }
  49. public void add(Task task) {
  50. try {
  51. queue.put(task);
  52. } catch (InterruptedException x) {
  53. return;
  54. }
  55. }
  56. public void run() {
  57. while (alive) {
  58. final Task task;
  59. try {
  60. task = queue.take();
  61. } catch (InterruptedException x) {
  62. break;
  63. }
  64. try {
  65. task.work();
  66. eventQueue.invokeLater(task);
  67. } catch (final Throwable t) {
  68. eventQueue.invokeLater(new Runnable() {
  69. public void run() {
  70. task.exception(t);
  71. }
  72. });
  73. }
  74. }
  75. }
  76. }