为什么我的代码在主线程上运行?

MTP*_*376 2 java multithreading android

我在onCreate方法中使用以下代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {


            @Override
            public void onClick(View arg0) {
                Thread thread = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            ServerSocket serverSocket = new ServerSocket(9002);
                            Socket s = serverSocket.accept();

                            DataOutputStream outputStream = new DataOutputStream(
                                    s.getOutputStream());
                            BufferedReader inputStream = new BufferedReader(
                                    new InputStreamReader(s.getInputStream()));

                            outputStream.write("Howdy! newbie".getBytes());

                            s.close();

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
                thread.run();
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

它给了我一个NetworkOnMainThreadException!

当我使用以下行删除限制时,它确实有效:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy); 
Run Code Online (Sandbox Code Playgroud)

但我为什么要用呢?

我使用了线程,为什么它不在分离的线程上运行并在UI线程上运行?!

Gir*_*hai 8

更改

thread.run();
Run Code Online (Sandbox Code Playgroud)

thread.start();
Run Code Online (Sandbox Code Playgroud)

区别:

Thread.run()不会产生新线程而Thread.start() 会产生,即Thread.run实际上在与调用者相同的线程上运行,同时Thread.start()创建一个运行任务的新线程.

有关更多信息,请参阅运行和启动线程之间的区别