在java中控制线程

时间:2016-07-23 15:46:49

标签: java multithreading runnable

我正在尝试创建一些东西,其中我必须提供两个可控线程,除了主要我可以启动,停止,暂停,恢复这些线程,我在抽象类中提供。这些线程将在后台执行一些专用功能。

目前我已经在其中创建了启动和停止功能,但我面临的问题是,在第二次启动后调用停止功能时,它不会停止。

我已经实现了将线程操作写入日志文件来测试这个,并观察到第二次当我调用stop函数时,它会陷入while循环,等待run函数中实现的循环完整。

有人可以帮助我找出导致此问题的原因,因为我对多线程不是什么新鲜事

以下是实施的课程

应控制主线程和辅助线程的控制器类:

package com.threadcontrol;

import com.threadcontrol.TimeStampGenerator;

public abstract class Controller {      

    private static Thread threadPrim=null;
    private static Thread threadSec=null;
    private static Status statusPrim=Status.NOT_STARTED;    
    private static Status statusSec=Status.NOT_STARTED; 
    private static boolean completedPrim=false; 
    private static boolean completedSec=false;
    private static RunnablePrim runnablePrim=new RunnablePrim();
    private static RunnableSec runnableSec=new RunnableSec();
    private static Logger loggerPrim=new Logger("LogPrim.txt");
    private static Logger loggerSec=new Logger("LogSec.txt");

    public enum Status {NOT_STARTED, RUNNING, PAUSED, STOPPED};
    public enum ThreadID {PRIM,SEC}

    private static class RunnablePrim implements Runnable
    {           
        @Override
        public void run() 
        {
            while(statusPrim==Status.RUNNING)
            {               
                loggerPrim.log(TimeStampGenerator.get() + " Running Prim:");                
            }               
            completedPrim=true;         
        }           
    }

    private static class RunnableSec implements Runnable
    {           
        @Override
        public void run() 
        {           
            while(statusSec==Status.RUNNING)
            {               
                loggerSec.log(TimeStampGenerator.get() + " Running Sec:");              
            }               
            completedSec=true;          
        }           
    }


    public static synchronized boolean start(ThreadID threadID)
    {   
        switch(threadID)
        {
            case PRIM:
                if(threadPrim==null)
                {
                    threadPrim=new Thread(runnablePrim,"Primary Thread");
                }
                statusPrim=Status.RUNNING;
                threadPrim.start();
                return true;
            case SEC:
                if(threadSec==null)
                {
                    threadSec=new Thread(runnableSec,"Secondary Thread");
                }
                statusSec=Status.RUNNING;
                threadSec.start();
                return true;            
        }
        return false;
    }

    public static synchronized boolean stop(ThreadID threadID)
    {       
        switch(threadID)
        {
            case PRIM:              
                statusPrim=Status.STOPPED;              
                while(completedPrim!=true)
                {

                }
                completedPrim=false;
                threadPrim=null;                    
                return true;
            case SEC:
                statusSec=Status.STOPPED;
                while(completedSec!=true)
                {

                }
                completedSec=false;
                threadSec=null;             
                return true;
        }
        return false;
    }

}

测试类:

package com.threadcontrol;

public class TestController {

    public static void main(String[] args) throws InterruptedException {

        int timeout=10;
        Logger logger=new Logger("LogMain.txt");

        logger.log(TimeStampGenerator.get() + " Starting Prim");
        Controller.start(Controller.ThreadID.PRIM);     
        Thread.sleep(timeout);
        logger.log(TimeStampGenerator.get() + " Starting Sec");
        Controller.start(Controller.ThreadID.SEC);
        Thread.sleep(timeout);
        logger.log(TimeStampGenerator.get() + " Stopping Prim");
        Controller.stop(Controller.ThreadID.PRIM);
        logger.log(TimeStampGenerator.get() + " Stopped Prim");
        Thread.sleep(timeout);
        logger.log(TimeStampGenerator.get() + " Stopping Sec");
        Controller.stop(Controller.ThreadID.SEC);
        logger.log(TimeStampGenerator.get() + " Stopped Sec");
        logger.log(TimeStampGenerator.get() + " Restarting");
        logger.log(TimeStampGenerator.get() + " Starting Prim");
        Controller.start(Controller.ThreadID.PRIM);     
        Thread.sleep(timeout);
        logger.log(TimeStampGenerator.get() + " Starting Sec");
        Controller.start(Controller.ThreadID.SEC);
        Thread.sleep(timeout);
        logger.log(TimeStampGenerator.get() + " Stopping Prim");
        Controller.stop(Controller.ThreadID.PRIM);
        logger.log(TimeStampGenerator.get() + " Stopped Prim");
        Thread.sleep(timeout);
        logger.log(TimeStampGenerator.get() + " Stopping Sec");
        Controller.stop(Controller.ThreadID.SEC);
        logger.log(TimeStampGenerator.get() + " Stopped Sec");
        logger.log(TimeStampGenerator.get() + " Exiting");

    }

}

Logger类,刚刚实现以测试线程行为:

package com.threadcontrol;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Logger {

    private static String projPath=System.getProperty("user.dir");
    private String filePath;

    public Logger(String fileName)
    {
        filePath=projPath + "\\data\\" + fileName;  
        File file=new File(filePath);
        try 
        {           
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, false)));
            out.flush();
            out.close();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void log(String data) 
    {           
        File file=new File(filePath);
        try 
        {           
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
            out.println(data);
            out.close();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }

}

TimeStampGenerator类,刚刚实现以测试线程行为:

package com.threadcontrol;

import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class TimeStampGenerator {  

    public static String get()
    {
        Date currentTimeStamp=new Date();
        SimpleDateFormat fmt=new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
        String tsStr=fmt.format(currentTimeStamp);
        return tsStr;
    }
}

主日志输出:

2016_07_23_21_01_11_160 Starting Prim
2016_07_23_21_01_11_320 Starting Sec
2016_07_23_21_01_11_331 Stopping Prim
2016_07_23_21_01_11_333 Stopped Prim
2016_07_23_21_01_11_345 Stopping Sec
2016_07_23_21_01_11_346 Stopped Sec
2016_07_23_21_01_11_347 Restarting
2016_07_23_21_01_11_348 Starting Prim
2016_07_23_21_01_11_359 Starting Sec
2016_07_23_21_01_11_371 Stopping Prim

1 个答案:

答案 0 :(得分:1)

因为你试图根据控制变量控制两个线程。对这4个成员使用volatile关键字。

private static volatile Status statusPrim=Status.NOT_STARTED;    
private static volatile Status statusSec=Status.NOT_STARTED; 
private static volatile boolean completedPrim=false; 
private static volatile boolean completedSec=false;

Do you ever use the volatile keyword in Java?