简体   繁体   中英

Is this a good practice in multithreading in android?

I have a thread that will run background and after that thread instantiate a string value, 4 more thread will run inside of that thread..

Is this a good practice in Threads base on android coding?

String name = null;

Thread a = new Thread(new First());
Thread b = new Thread(new Enemy());
Thread c = new Thread(new Enemy());
Thread d = new Thread(new Enemy());
Thread e = new Thread(new Enemy());
a.start();

class First implements Runnable {
    public void run() {
         name = "TARZAN";
         b.start();
         c.start();
         d.start();
         e.start();
    }
}

class Enemy implements Runnable {
    public void run() {
         System.out.println(Thread.currentThread().getName() + name);
    }
}

Is this a good practice performing a 4 runnable classes inside from a first thread?

Threads don't run inside threads. But what you're doing isn't spawning off 4 new threads- you're just calling them as methods inside your first thread. To spawn them as new threads you need to use .start(), not .run(). So if .run() is really what you want then I'd say it's a bad idea because there's no reason to make those threads at all. If you really wanted to use .start() and launch a new thread, I'd say its fine so long as you have a good reason for doing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM