0

I've been trying to connect to a server to retrieve some data. First thing came to my mind was to create a thread to connect asynchronously.

new Thread(new Runnable() {
    @Override
    public void run() {
        // retrieve data
    }
}).run();

But the weird thing is that the thread I created worked synchronous with UI thread and I got a network exception so I ended up using AsyncTask. Do you guys know what could cause a thread to work non asynchronously with the UI thread? My class extends to a fragment.

Barışcan Kayaoğlu
  • 1,294
  • 3
  • 14
  • 35

1 Answers1

5

Your must start your thread with start() and not run() in order to start the new thread:

new Thread(new Runnable() {
    @Override
    public void run() {
        // retrieve data
    }
}).start();
makovkastar
  • 5,000
  • 2
  • 30
  • 50
  • Yes I think that was the problem. But what's the difference between run and start? I could only see the exception throwing between them. – Barışcan Kayaoğlu Apr 09 '14 at 11:55
  • 1
    run() runs on the same thread as the caller's, whereas start() starts a new Thread. – NickT Apr 09 '14 at 12:04
  • 1
    @BarışcanKayaoğlu when you use `Thread.run()` the `run()` method of that Runnable that you passed to the Thread constructor is called in the same thread. – makovkastar Apr 09 '14 at 12:10