Threads in Java

前端 未结 9 900
野趣味
野趣味 2020-11-30 01:11

I was today asked in an interview over the Thread concepts in Java? The Questions were...

  1. What is a thread?
  2. Why do we go for threading?
  3. A re
9条回答
  •  余生分开走
    2020-11-30 01:50

    To create threads, create a new class that extends the Thread class, and instantiate that class. The extending class must override the run method and call the start method to begin execution of the thread.

    Inside run, you will define the code that constitutes a new thread. It is important to understand that run can call other methods, use other classes and declare variables just like the main thread. The only difference is that run establishes the entry point for another, concurrent thread of execution within your program. This will end when run returns.

    Here's an example:

    public class MyThread extends Thread {
        private final String name;
    
        public MyThread(String name) {
            this.name = name;
        }
    
        public void run() {
            try {
                for (; ; ) {
                    System.out.println(name);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                System.out.println("sleep interrupted");
            }
        }
    
        public static void main(String[] args) {
            Thread t1 = new MyThread("First Thread");
            Thread t2 = new MyThread("Second Thread");
            t1.start();
            t2.start();
        }
    }
    

    You will see this on the screen:

    First Thread
    Second Thread
    First Thread
    Second Thread
    First Thread
    

    This tutorial also explains the Runnable interface. With Spring, you could use a thread pool.

提交回复
热议问题