jdk 1.4
我在程序里面自己创建了一组线程处理任务.
每个线程都是无限循环从任务列表获取任务,处理完成后再到任务列表获取下个任务.如果任务列表没有任务则休眠500毫秒再次从任务列表获取任务.
代码如下public class AutoAcceptThread  implements Runnable{
private static final Log log = LogFactory.getLog(AcceptThread.class);
private List waitList;
private DataSource crmDataSource;
private SvrUpdate svrUpdate;
private String threadName;
private volatile boolean canRun;
private volatile long runtime=0;
public void run() { while(canRun){

try{
                                    //记录线程当前运行时间
runtime=System.currentTimeMillis();
                                     //得到任务
Map indentMap=getIndent();
if(indentMap==null){
                                     //没有任务休眠500毫秒.
try{
Thread.sleep(500);
}catch(Exception e){
if(log.isErrorEnabled()){
log.error("Thread.sleep-error"+e);
}
}
continue;
}
try{
//做任务
}catch(Exception ee){

if(log.isErrorEnabled()){
log.error(ee);
}
}finally{


}
}catch(Exception e){
if(log.isErrorEnabled()){
log.error(e);
}
}

}
//退出时打日志
log.debug("-------------end!");          
}
}现在可能有一些原因,我在其他线程内设置该线程设置 canRun =false ,有些情况下线程退出会打日志 "------------end!"
有些情况线程不再执行循环,也不会打退出日志??? 

解决方案 »

  1.   


    package thread;public class ProducerAndCustomerDemo {
    public static void main(String[] args) {
    Queue q=new Queue();
    Productor p=new Productor(q);
    Customer c=new Customer(q);
    p.start();
    c.start();
    }
    }
    class Customer extends Thread{
    Queue q;
    public Customer(Queue q) {
    // TODO Auto-generated constructor stub
    this.q=q;
    }
    @Override
    public void run() {
    // TODO Auto-generated method stub
    while (q.value<10) {
    System.out.println("Customer get "+q.get());
    }
    }
    }
    class Productor extends Thread{
    Queue q;
    public Productor(Queue q) {
    // TODO Auto-generated constructor stub
    this.q=q;
    }
    @Override
    public void run() {
    // TODO Auto-generated method stub
    for (int i = 1; i <=10; i++) {
    q.put(i);
    System.out.println("Productor put "+i);
    }
    }
    }
    class Queue{
    int value;
    boolean bFull=false;
    public synchronized void  put(int i){
    if (!bFull) {
    value=i;
    bFull=true;
    //notify();
    notifyAll();
    try {
    wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    public synchronized int get(){
    if (!bFull) {
    try {
    wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    bFull=false;
    notifyAll();
    return value;
    }
    }