Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: jpl2/common/WorkerThread.java


1   /***********************************************************************
2    *   JavaPsionLink 2.0, a java implementation of the psion link protocol
3    *   Copyright (C) 2002, 2003  John S Montgomery (john.montgomery@lineone.net)
4    *
5    *   This program is free software; you can redistribute it and/or modify
6    *   it under the terms of the GNU Lesser General Public License as published by
7    *   the Free Software Foundation; either version 2.1 of the License, or
8    *   (at your option) any later version.
9    *
10   *   This program is distributed in the hope that it will be useful,
11   *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   *   GNU Lesser General Public License for more details.
14   *
15   *   You should have received a copy of the GNU General Public License
16   *   along with this program; if not, write to the Free Software
17   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   ************************************************************************/
19  package jpl2.common;
20  
21  
22  import java.util.Vector;
23  
24  public class WorkerThread extends Thread {
25    private Vector queue = new Vector();
26    private volatile boolean running = true;
27    
28    public WorkerThread() {
29      super( "WorkerThread" );
30      setDaemon( true );
31    }
32    
33    public synchronized void quit() {
34      running = false;
35      notifyAll();
36    }
37    
38    public synchronized void schedule( Runnable runner ) {
39      //System.out.println( "Scheduled: " + runner );
40      queue.addElement( runner );
41      notifyAll();
42    }
43    
44    public void run() {
45      while( true ) {
46        
47        synchronized( this ) {
48          if ( running && queue.size() == 0 ) {
49            try {
50              wait();
51            }
52            catch( Exception e ) {
53              continue;
54            }
55            if ( !running )
56              break;
57          }
58        }
59        
60        Runnable runner = (Runnable)queue.elementAt( 0 );
61        queue.removeElementAt( 0 );
62        
63        //System.out.println( "starting " + runner );
64        try {
65          runner.run();
66        }
67        catch( Throwable t ) {
68          t.printStackTrace();
69        }
70        //System.out.println( "finished " + runner );
71      }
72    }
73  
74  }