1 6 7 package org.jfox.pool.thread; 8 9 import org.jfox.pool.ObjectPool; 10 11 12 15 16 public class PoolableThreadImpl extends Thread implements PoolableThread { 17 private boolean available = false; 18 private ThreadTask task = null; 19 private volatile boolean running = false; 20 private static volatile long threadId = 0L; 21 private volatile boolean waiting = false; 22 23 public PoolableThreadImpl() { 24 super("PoolableThread: " + threadId++); 25 start(); 26 while(!waiting) { synchronized(this) { 28 try { 29 this.wait(1L); 30 } 31 catch(InterruptedException e) { 32 e.printStackTrace(); 33 } 34 } 35 } 36 } 37 38 public void run() { 39 running = true; 40 do { 41 if(!running) break; 42 try { 43 synchronized(this) { 44 waiting = true; 45 wait(); 46 } 47 } 48 catch(InterruptedException e) { 49 e.printStackTrace(); 50 waiting = false; 51 if(!running || task == null) break; 52 } 53 54 waiting = false; if(task == null) break; try { 57 task.getTask().run(); 58 } 59 catch(Exception e) { 60 } 61 finally { 62 synchronized(this) { 64 ObjectPool pool = task.getPool(); 65 synchronized(pool) { 66 pool.restoreObject(this); 67 } 68 } 69 } 70 71 } while(true); 72 } 73 74 public void activate() throws Exception { 75 available = true; 77 running = true; 78 79 } 80 81 public void passivate() throws Exception { 82 available = false; 84 task = null; 85 } 86 87 public boolean isAvailable() { 88 return available; 89 } 90 91 public void setTask(ThreadTask task) { 92 if(waiting == true) { 94 this.task = task; 95 synchronized(this) { 96 notify(); 97 } 98 } 99 } 100 101 public void discard() { 102 running = false; 103 synchronized(this) { 104 notifyAll(); 105 } 106 task.getPool().removeObject(this); 107 } 108 109 public long getSleepTime() { 111 return 0; 112 } 113 114 } | Popular Tags |