Why does starting my thread not call the run() method?

时间:2015-05-12 23:39:39

标签: java multithreading

In the first method, I just want to create a thread for each URL in the array and parse it:

% 47

And then I made a separate class for my runnable object, where the run method creates a bufferedReader to scan the html file and parses it.

    public void readFriendData(String[] urls) {
    Thread[] urlThreads = new Thread[urls.length];
    for (int x = 0; x < urls.length; x++) {
        Runobject input = new Runobject(urls[x], this);
        Thread one = new Thread(input);
        urlThreads[x] = one;

    }

    for(int x = 0; x< urls.length; x++){
        urlThreads[x].start();
    }
}

I know when the first method is called, even though I started the threads, it doesn't go through the run method in the runObject class. Why is this?

2 个答案:

答案 0 :(得分:1)

您的代码完美无缺。你根本没有意识到这一点。添加一些日志/输出消息,您将看到它。哦,顺便说一句,预计输入结束。这是简化的代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class Runobject implements Runnable {
    public String address;

    public static void main(String a[]) {
        System.out.println("Start");
        readFriendData(new String[] { "http://google.com", "http://yahoo.com" });
        System.out.println("End");
    }

    public static void readFriendData(String[] urls) {
        Thread[] urlThreads = new Thread[urls.length];
        for (int x = 0; x < urls.length; x++) {
            Runobject input = new Runobject(urls[x]);
            Thread one = new Thread(input);
            urlThreads[x] = one;

        }

        for (int x = 0; x < urls.length; x++) {
            urlThreads[x].start();
        }
    }

    public Runobject(String theAdress) {
        address = theAdress;
        System.out.println(address);
    }

    @Override
    public void run() {
        try {
            URL url = new URL(address);
            URLConnection urlConnection = url.openConnection();

            BufferedReader scanner = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));

            int countOfLines = 0;
            String input = scanner.readLine();
            while (input != null && !input.equals("</body>")) {
                countOfLines++;
                if (input.startsWith("<tr> <td>addperson</td>")) {
                    input.replaceAll("<tr> <td>addperson</td>", "");
                    input.replaceAll(" <td>", "");
                    input.replaceAll("</td> </tr>", "");

                    // net.addUser(input);
                } else if (input.startsWith("<tr> <td>addfriend</td>")) {
                    String[] bits = new String[2];
                    input.replaceAll("<tr> <td>addfriend</td>", "");
                    bits = input.split("</td> <td>");
                    input.replaceAll(" <td>", "");
                    input.replaceAll("</td> </tr>", "");

                    // net.friend(bits[0], bits[1]);
                    // net.friend(bits[1], bits[0]);

                }

                input = scanner.readLine();

            }
            scanner.close();
            System.out.println(address + " has " + countOfLines + " lines");
        } catch (IOException e) {
            System.out.println("bad URL");
        }
    }    
}

这是输出:

Start
http://google.com
http://yahoo.com
End
http://google.com has 8 lines
http://yahoo.com has 63 lines

请注意,当您的读者刚刚开始时,您的主要线程已经完成。一个词 - 多线程。

答案 1 :(得分:0)

虽然,我不喜欢它的质量。我知道我不是代码审查员。请试试这个!

 public class Container<E> {
    private LinkedList<E> data;

     public Container() {
        this.data = new LinkedList<E>();
    }

    public Container(final Container<E> other) {
        this.data = new LinkedList<E>(other.data);
    }

    public Container<E> add(E e) {
        Container<E> other_cont= new Container<E>(this);
        other_cont.data.add(e);
        return other_cont;
    }

    public Container<E> remove() {
        Container<E> other_cont= new Container<E>(this);
        other_cont.data.remove(0);
        return other_cont;
    }

     public E peek() {
        if(this.data.isEmpty())
            throw new NoSuchElementException("No element to peek at");
        return this.data.get(0);
    }

     public int size() {
        return this.data.size();
    }
 }

这里的RunObject类

public static void main(String[] args) {
    Twitbook twitbook = new Twitbook();
    String[] urls = new String[2];
    urls[0] = "www.google.com";
    urls[0] = "www.yahoo.com";
    twitbook.readFriendData(urls);
}

public void readFriendData(String[] urls) {
    CountDownLatch latch = new CountDownLatch(urls.length);
    for (int x = 0; x < urls.length; x++) {
        Runobject input = new Runobject(urls[x], this, latch);
        input.run();
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return;
}

public synchronized void addUser(String input) {

    return;
}

public synchronized void friend(String bits1, String bits2) {

    return;
}

请考虑更好的设计。这些链接可以帮助您做更好的编码。

线程池是一个不错的选择 http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

CountDownLatch用于完成所有线程http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

Runobject也可以是私有的内部类。 Wait until child threads completed : Java

免责声明: - 在其他问题和答案的帮助下回答。