2

私はマルチスレッドにほとんど慣れていないので、これからする質問は簡単かもしれません。

私のプログラムには 2 つのスレッドがあり、1 つはメインスレッド、もう 1 つはmythreadです。

package multithreading;

public class ThreadDemo {
    public static void main(String args[]) {        
        System.out.println(Thread.currentThread());
        new MyThread();
        try {
            for(int i = 1; i<=5; i++) {                             
                Thread.sleep(1000);
            }

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}

class MyThread extends Thread {
    public MyThread() {     
        start();
    }

    public void run() {
        Thread.currentThread().setName("mythread");
        System.out.println(Thread.currentThread());
        for(int i = 1; i<=5; i++) {
            try {
                Thread.sleep(500);
                //System.out.println("MyThread i value "+i);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

さて、プログラムの出力は、

Thread[main,5,main]
Thread[mythread,5,main]

出力の意味はわかっています。

しかし、 mythreadのスレッド グループをmainではなく自分のものに変更したいと考えています。これどうやってするの?

スレッドのスレッドグループを変更するために使用される Java メソッドは?

スレッドグループを変更することで何か問題はありますか?

4

4 に答える 4

5

Thread を拡張する代わりに Runnable を実装することをお勧めします。その後、独自のグループを持つ新しいスレッドを簡単に作成できます。

public class ThreadDemo {
   public static void main(String args[]) {
        System.out.println(Thread.currentThread());
        Runnable r = new MyRunnable();
        new Thread(new ThreadGroup("my group"), r).start();
        try {
            for (int i = 1; i <= 5; i++) {
                Thread.sleep(1000);
            }

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class MyRunnable implements Runnable {

    public void run() {
        Thread.currentThread().setName("mythread");
        System.out.println(Thread.currentThread());
        for (int i = 1; i <= 5; i++) {
            try {
                Thread.sleep(500);
                //System.out.println("MyThread i value "+i);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
于 2013-07-16T10:31:38.273 に答える
4

You should create your own ThreadGroup and use Thread(ThreadGroup group, String name) constructor to create a Thread:

class MyThread extends Thread {
    public MyThread(ThreadGroup tg, String name) {
        super(tg, name);
        start();
    }

...

ThreadGroup tg = new ThreadGroup("mythreadgroup");
new MyThread(tg, "mythread");
于 2013-07-16T10:40:33.277 に答える