Sunday, June 7, 2020

7.1. Multithreading in JAVA

1. What is Multi threading?
The process of executing two or more threads concurrently, where each thread responsible for different task at the same time is called as multi threading.

2. Difference between sleep() and wait()

3. How to call a thread? 
  • Threads may not execute sequentially, meaning thread 1 may not be the first to write its name to System.out. This is because the threads are principle executing in parallel and not sequentially. The JVM and/or operating system determines the order in which the threads are executed. This order does not have to be same order in which they were started.
  • Main threads automatically start by JVM and the other user defined threads calls by using start() method.

4. Can Java thread object invoke start method twice?
No. After starting a thread, it can never be started again. If you do so, an IllegalThreadStateException is thrown. In such a case, thread will run once but for a second time, it will throw an exception.

5. What is Daemon thread?
Daemon thread is a low priority thread,works with JVM when all the user threads finishes their execution, JVM doesn't care whether Daemon thread is running or not because it terminates the thread and after that shutdown itself.
Example:
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().setDaemon(true);
System.out.println(Thread.currentThread().isDaemon());
       }
}
Output:
True


6. Can we change the name of the main thread ?

Yes, we can change the name of the main thread. It can be done by first getting the reference of the main thread by using currentThread() method and then calling setName() method on it.
For example:
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread t=Thread.currentThread();
t.setName("Durga");
                System.out.println(t.getName() +"Thread");
        }
}
Output:
Durga Thread.

No comments:

Post a Comment