Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my code running on the main thread?

I'm using the following code in my onCreate method:

@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();
            }
        });
    }

It gives me a NetworkOnMainThreadException!

It does work when I use the following lines to remove the restriction:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy); 

But why should I use it?

I used thread, why isn't it running on the separated thread and runs on the UI thread?!

like image 552
Mohammad Teimori Pabandi Avatar asked Feb 06 '26 17:02

Mohammad Teimori Pabandi


2 Answers

Change

thread.run();

to

thread.start();

Difference:

Thread.run() does not spawn a new thread whereas Thread.start() does, i.e Thread.run actually runs on the same thread as that of the caller whereas Thread.start() creates a new thread on which the task is run.

For more info see Difference between running and starting a thread

like image 155
Giru Bhai Avatar answered Feb 09 '26 06:02

Giru Bhai


Because you are not asking the thread to start.

Replace:

thread.run();

With

thread.start();

Calling run() will simply execute the provided Runnable on the current thread. However, start() will spawn the execution onto a new thread.

like image 24
waqaslam Avatar answered Feb 09 '26 06:02

waqaslam