多线程在一种运行方法中执行不同的任务

时间:2015-12-11 13:45:43

标签: java multithreading java-threads

我是执行多线程的新手。

我想要2个不同名称的线程。但它不会发生。它取名字的最后一个。

这是我的班级'扩展线程的代码:

    public class Asallik extends Thread {
        public static ArrayList<Thread> t2;
        public static ArrayList<String> str;
        public static ArrayList<Asallik> d;
        public int i = 0;
        public Asallik(String threadName) {
            t2.add(new Thread(this, threadName));
            t2.get(i).start();    
            i++;    
        }

        public static void createThread() {
            str = new ArrayList();
            t2 = new ArrayList();

            for (int i = 0; i < 2; i++) {
                str.add("Thread " + String.valueOf(i));
                d.add(new Asallik(str.get(i)));
            }

        }

        @Override
        public void run() {
            System.out.println("I came " + this.getName());
            if (t2.get(0).getName().equals("Thread 0")) {
                System.out.println("Thread 0 arrived");
            } else if (t2.get(1).getName().equals("Thread 1")) {
                System.out.println("Thread 1 arrived");
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println("Error : " + e);
            }
        }

    }

这是主要代码:

package deneme2;

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {        
        Asallik.createThread();
    }
}

我试过这种方式,但我无法做到。有没有办法在一个运行方法中执行多线程但名称不同?

结果如下:

I came Thread-0
Exception in thread "main" java.lang.NullPointerException
Thread 0 arrived
    at deneme2.Asallik.createThread(Asallik.java:32)
    at deneme2.Main.main(Main.java:19)
Java Result: 1

2 个答案:

答案 0 :(得分:0)

public Asallik(String threadName) {

    //this class extends Thread so you can call Thread methods
    setName(threadName);
    t2.add(this);
    start();
    //I changed everything above this comment to the next

    i++;
}

public static void createThread() {
    str = new ArrayList();
    t2 = new ArrayList();
    d = new ArrayList(); //initialize d <-------------------
    for (int i = 0; i < 2; i++) {
        str.add("Thread " + String.valueOf(i));
        d.add(new Asallik(str.get(i)));
    }
}

答案 1 :(得分:0)

希望这个帮助

Black