1

这是类投资组合:

public class Portfolio extends Thread {
    private volatile Thread stopMe= Thread.currentThread();
            
    public Portfolio(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }
    public void stopMe(){
        stopMe= null;
    }

    @Override
    public void run() {
        while(stopMe== Thread.currentThread()){
        try {
            for(int i=0; i<10; i++){
            //sleep(700);   
            System.out.println("You have " +(500+i)+ " shares of IBM");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(Thread.currentThread().getName()+e.toString());
        }}
    }

    
}

这是我调用线程的地方

public class TestThreads {

    /**
     * @param args
     */
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MarketNews mn= new MarketNews("Market News");
        mn.start();
        //mn.setPriority(Thread.NORM_PRIORITY+1);
        //mn.interrupt();
        mn.isAlive();       
        Portfolio p= new Portfolio("Portfolio data");
        p.start();
    //  System.out.println(Thread.currentThread().interrupted());
        System.out.println("TestThreads is finished");
        
    }

}

我调用了 p.start(),但它似乎不起作用。当我删除 stopMe 变量时,代码工作正常。

4

1 回答 1

5

当你运行时:

Portfolio p= new Portfolio("Portfolio data");

stopMe 是“主”线程(当前线程)

然后

p.start()

你开始一个新的,所以 stopMe 与那个线程不同,投资组合中的“运行”功能将直接停止

于 2012-04-18T19:09:53.877 回答