如果我们在start方法而不是run方法中执行整个Thread功能会发生什么?

时间:2018-05-25 11:00:44

标签: java multithreading java-threads

如果我们在start方法而不是run方法中执行整个Thread功能会发生什么?下面的代码运行方式与在run方法中添加代码时运行的方式相同...

   public class RunMethodTest extends AppCompatActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Abc abc=new Abc();
        abc.start();
    }
}

class Abc extends Thread
{
    @Override
    public synchronized void start() {
        super.start();
        for(int i=0;i<10;i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread" + " " + i);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

测试它:让你的代码通过

告诉你它正在调用哪个线程
  1. 通过Thread.currentThread()
  2. 获取当前主题
  3. 然后通过getId()getName()
  4. 获取当前主题的ID和姓名

    public class ThreadTest {
        public static void main(String[] args) {
            Thread currentThread = Thread.currentThread();
            System.out.printf("Main, Which Thread: %s, %d%n", 
                    currentThread.getName(), 
                    currentThread.getId());
    
            Abc abc = new Abc();
            abc.start();
        }
    }
    

    class Abc extends Thread {
        @Override
        public synchronized void start() {
            super.start();
    
            Thread currentThread = Thread.currentThread();
            System.out.printf("Start, Which Thread: %s, %d%n", 
                    currentThread.getName(), 
                    currentThread.getId());
    
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread" + " " + i);
            }
        }
    
        @Override
        public void run() {
            super.run();
    
            Thread currentThread = Thread.currentThread();
            System.out.printf("Run, Which Thread: %s, %d%n", 
                    currentThread.getName(), 
                    currentThread.getId());
        }
    }
    

    对我来说,这会返回:

    Main, Which Thread: main, 1
    Start, Which Thread: main, 1
    Run, Which Thread: Thread-0, 9
    Thread 0
    Thread 1
    Thread 2
    Thread 3
    ....
    

    这证明你的Abc的start方法(正如预期的那样)在与调用代码相同的线程中调用而不是在新线程中调用,并且只有run()方法中的代码在新的内部被调用线。如上所述,您几乎从不需要或想要扩展Thread,而是实现Runnable或Callable。