Jump to content

Threads In Java... WTF?


obasan

Recommended Posts

I legit don't understand wtf is the point of them. This is the example code:

 

class Loader extends Thread {
    public void run() {
        System.out.println(“Hello”);
    }
}

class Program {
    public static void main(String[] args) {
        Loader load = new Loader();
        //load.setPriority(10);
        load.start();
    }
}

 

 

So what's the point of using Threads? Can somebody please explain the usefulness of this?

Are threads good because you can optimize the program and spilt the work between two processors?

Or maybe they're good because you can change priority and make certain calculations more important than others?

Edit: wtf is the runnable interface? I know its another way of creating threads but whats the point?

 

Please & Thank You

Edited by obasan
Link to comment
Share on other sites

Imagine if you have a webserver that only operates on 1 thread synchronously. It could only handle one request at a time. Lets say a user visits and another user visits 1 second after, it has to grab his data from the database, do whatever calculations etc, and resolve the first users request before being able to even recognize the second user has sent a request to the website. This is due to the only thread being blocked from the first request, so no other requests can be considered.

  • Like 1
Link to comment
Share on other sites

The most important thing to understand with threads is that they run concurrently. Imagine you have a program that has a GUI with a button in it. If the button is pressed and you'd execute some heavy calculation (or wait for something) in the same thread (the GUI is running on and being repainted in) ... the whole application would go unresponsive. By using another thread to do the calculation it will keep responsive. It's generally much better to work with Runnables instead of threads as it's much more flexible. Also look up ExecutorService to run them properly.

  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...