如何在java类中放置一个可运行的线程

时间:2013-09-20 19:44:28

标签: java multithreading url

首先,我以前从未使用过线程,所以请原谅任何松散的术语。我有三个相似但不同的类,所有这些都需要从互联网上读取信息,所以我想创建一个在后台运行的线程,而程序使用它在线的本地副本。但是,每个类都需要自己的特殊输入,因此我不能创建一个主要的runnable类。

问题:我应该制作三个单独的线程,每个程序一个,还是可以在每个类中嵌入一个Runnable线程?我该怎么做?

感谢您的帮助

PS。如果你想看我的程序(至少是它的一个版本),请转到jacobfakult.50webs.com/quizzes/program ...对不起该广告,再次感谢!

3 个答案:

答案 0 :(得分:1)

由于之前从未使用过线程,我不会给你一个直接的答案,所以我建议你先阅读这个主题。这是官方资源:Lesson: ConcurrencyExecutors

阅读完所有内容后,您现在将了解到您希望使用能够为您处理线程的ExecutorService。现在唯一重要的是当前的应用程序设计,它将在每个线程上完成工作,在这种情况下,从Internet下载内容。

简单方式:让您的三个(或更多)类实现Runnable接口,并在run方法中完成所有工作。例如:

public class Foo implements Runnable {
    @Override
    public void run() {
        doWork();
    }
    public void doWork() {
        //download files or whatever you want/need to do
    }
}

public class BigWorker {
    private static final int NUM_OF_THREADS = 3;
    public void doWork() {
        ExecutorService es = Executors.newFixedThreadPool(NUM_OF_THREADS);
        es.execute(new Foo());
        //assuming Bar and Baz are the other two classes...
        es.execute(new Bar());
        es.execute(new Baz());
        //it is A MUST to call this method
        es.shutdown();
    }
}

答案 1 :(得分:0)

我对这个问题不太熟悉,但这是我的两分钱(免费):

  1. 有一个后台线程来处理需要下载信息的所有三个类的请求。
  2. 拥有一个请求列表,以便后台线程可以同步处理请求。
  3. 当班级需要下载信息时,只需添加到该请求列表
  4. 经过一些谷歌搜索后,你可以拥有的线程数量没有限制,但是线程数越多,每个线程提供的好处就越少。在我看来,一个线程就足以完成你的任务。

    示例:

    //maybe make an Request class that specifies the url of what you want to download,
    //and what to do with response
    //put this ArrayList as a member field in the class you are making the thread
    ArrayList<Request> requests = new ArrayList<Request>();
    
    Thread backgroundThread = new Thread(){
        public void run(){
            while(true)
                {
                    if(requests.size() > 0)
                    {
                        Request oldestRequest = requests.get(0);
    
                        //process the request
    
                        test.remove(0);
                    }
                    else
                    {
                        //checks every 10 seconds if there is a request
                        Thread.sleep(10000);
                    }
                }
            }
        };
    backgroundThread.start();
    

答案 2 :(得分:0)

    /*
     * i dont understand totally what your point is, but assume
     * we have 3 classes that needs to use one Runnable task ...
     * Threads are Runnable ... any way, so
     */

    // create your runnable task
    class ReadDataOnline implements Runnable{

        @Override
        public void run() {
            // read data from the internet and update something or what ever
        }
    }


    // create your classes that will use this task
    class ClassOne{
        private ReadDataOnline runnable = null;
        private Thread reader = null;

        ClassOne(ReadDataOnline runnable){
            this.runnable = runnable;
            reader = new Thread(runnable);
        }

        void useTask(){
            // start your new Thread in the background, which will use
            // the Runnable task in the parameter
            reader.start();
        }
    }

    class ClassTwo {
        private ReadDataOnline runnable = null;
        private Thread reader = null;

        ClassTwo(ReadDataOnline runnable) {
            this.runnable = runnable;
            reader = new Thread(runnable);
        }

        void useTask() {
            // start your new Thread in the background, which will use
            // the Runnable task in the parameter
            reader.start();
        }
    }

    class ClassThree {
        private ReadDataOnline runnable = null;
        private Thread reader = null;

        ClassThree(ReadDataOnline runnable) {
            this.runnable = runnable;
            reader = new Thread(runnable);
        }

        void useTask() {
            // start your new Thread in the background, which will use
            // the Runnable task in the parameter
            reader.start();
        }
    }


    class MainClass{

        public void doStuff(){

            ReadDataOnline runnable = new ReadDataOnline();

            // use the same runnable task in the three classes
            ClassOne classOne = new ClassOne(runnable);
            ClassTwo classTwo = new ClassTwo(runnable);
            ClassThree classThree = new ClassThree(runnable);

            // let classOne start using the Task
            classOne.useTask();

            // now the Task status is updated/modified by classOne,
            // let classTwo use the task in it's new state
            classTwo.useTask();

            // and so on
            classThree.useTask();

            /*
             * since we are not talking about a specefic case, i cant tell
             * what is the task or what to do with it, but put in mind that
             * synchronizing your methods is very important since multi-threading
             * doesnt guarantee the order of the threads, and also they wont
             * be synchronized with each other unless your methods are synchronized 
             * (or you use synchronization blocks)
             */

            // i know this example isnt very good, but at least it shows how to use
            // the same task in multiple Threads or classes that are backed with
            // different threads



        }


    }