Which of the following methods will start this public class Mythread implements runnable public void run () some code here?

Q. What are the states in the lifecycle of a Thread?

A java thread can be in any of following thread states during it's life cycle i.e. New, Runnable, Blocked, Waiting, Timed Waiting or Terminated. These are also called life cycle events of a thread in java.

  • New
  • Runnable
  • Running
  • Non-Runnable [Blocked]
  • Terminated

1. New: The thread is in new state if you create an instance of Thread class but before the invocation of start[] method.
2. Runnable: The thread is in runnable state after invocation of start[] method, but the thread scheduler has not selected it to be the running thread.
3. Running: The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable [Blocked]: This is the state when the thread is still alive, but is currently not eligible to run.
5. Terminated: A thread is in terminated or dead state when its run[] method exits.

Q. What are the different ways of implementing thread?

There are two ways to create a thread:

  • extends Thread class
  • implement Runnable interface

1. Extends Thread class
Create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run[] method which is the entry point of new thread.

public class MyThread extends Thread { public void run[] { System.out.println["Thread started running.."]; } public static void main[ String args[] ] { MyThread mt = new MyThread[]; mt.start[]; } }

Output

2. Implementing the Runnable Interface
After implementing runnable interface, the class needs to implement the run[] method, which is public void run[].

  • run[] method introduces a concurrent thread into your program. This thread will end when run[] returns.
  • You must specify the code for your thread inside run[] method.
  • run[] method can call other methods, can use other classes and declare variables just like any other normal method.

    class MyThread implements Runnable { public void run[] { System.out.println["Thread started running.."]; } public static void main[String args[]] { MyThread mt = new MyThread[]; Thread t = new Thread[mt]; t.start[]; } }

Difference between Runnable vs Thread

  • Implementing Runnable is the preferred way to do it. Here, you’re not really specializing or modifying the thread's behavior. You’re just giving the thread something to run. That means composition is the better way to go.
  • Java only supports single inheritance, so you can only extend one class.
  • Instantiating an interface gives a cleaner separation between your code and the implementation of threads.
  • Implementing Runnable makes your class more flexible. If you extend Thread then the action you’re doing is always going to be in a thread. However, if you implement Runnable it doesn’t have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application.

Q. What is the difference between Process and Thread?

Both processes and threads are independent sequences of execution. The typical difference is that threads run in a shared memory space, while processes run in separate memory spaces.

Process

  • An executing instance of a program is called a process.
  • Some operating systems use the term task to refer to a program that is being executed.
  • A process is always stored in the main memory also termed as the primary memory or random access memory.
  • Therefore, a process is termed as an active entity. It disappears if the machine is rebooted.
  • Several process may be associated with a same program.
  • On a multiprocessor system, multiple processes can be executed in parallel.
  • On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.

Thread

  • A thread is a subset of the process.
  • It is termed as a lightweight process, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel.
  • Usually, a process has only one thread of control – one set of machine instructions executing at a time.
  • A process may also be made up of multiple threads of execution that execute instructions concurrently.
  • Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.
  • On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.
  • All the threads running within a process share the same address space, file descriptors, stack and other process related attributes.
  • Since the threads of a process share the same memory, synchronizing the access to the shared data within the process gains unprecedented importance.

Q. What is difference between user Thread and daemon Thread?

Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks.

Difference Between Daemon Threads And User Threads In Java

  • User threads are created by the application [user] to perform some specific task. Where as daemon threads are mostly created by the JVM to perform some background tasks like garbage collection.

  • JVM will wait for user threads to finish their tasks. JVM will not exit until all user threads finish their tasks. On the other side, JVM will not wait for daemon threads to finish their tasks. It will exit as soon as all user threads finish their tasks.
  • User threads are high priority threads, They are designed mainly to execute some important task in an application. Where as daemon threads are less priority threads. They are designed to serve the user threads.
  • User threads are foreground threads. They always run in foreground and perform some specific task assigned to them. Where as daemon threads are background threads. They always run in background and act in a supporting role to user threads.
  • JVM will not force the user threads to terminate. It will wait for user threads to terminate themselves. On the other hand, JVM will force the daemon threads to terminate if all the user threads have finished their task.

create Daemon Thread

/** * Java Program to demonstrate difference beween a daemon and a user thread . * */ public class DaemonThreadDemo { public static void main[String[] args] throws InterruptedException { // main thread is a non-daemon thread String name = Thread.currentThread[].getName[]; boolean isDaemon = Thread.currentThread[].isDaemon[]; System.out.println["name: " + name + ", isDaemon: " + isDaemon]; // Any new thread spawned from main is also non-daemon or user thread // as seen below: Runnable task = new Task[]; Thread t1 = new Thread[task, "T1"]; System.out.println["Thread spawned from main thread"]; System.out.println["name: " + t1.getName[] + ", isDaemon: " + t1.isDaemon[]]; // though you can make a daemon thread by calling setDaemon[] // before starting it as shown below: t1.setDaemon[true]; t1.start[]; // let's wait for T1 to finish t1.join[]; } private static class Task implements Runnable { @Override public void run[] { Thread t = Thread.currentThread[]; System.out.println["Thread made daemon by calling setDaemon[] method"]; System.out.println["name: " + t.getName[] + ", isDaemon: " + t.isDaemon[]]; // Any new thread created from daemon thread is also daemon Thread t2 = new Thread["T2"]; System.out.println["Thread spawned from a daemon thread"]; System.out.println["name: " + t2.getName[] + ", isDaemon: " + t2.isDaemon[]]; } } }

Output

name: main, isDaemon: false Thread spawned from main thread name: T1, isDaemon: false Thread made daemon by calling setDaemon[] method name: T1, isDaemon: true Thread spawned from a daemon thread name: T2, isDaemon: true

Q. How does thread communicate with each other?

Inter-thread communication is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter [or lock] in the same critical section to be executed. It is implemented by following methods of Object class:

  • wait[]
  • notify[]
  • notifyAll[]

class ThreadA { public static void main[String [] args] { ThreadB b = new ThreadB[]; b.start[]; synchronized[b] { try { System.out.println["Waiting for b to complete..."]; b.wait[]; } catch [InterruptedException e] {} System.out.println["Total is: " + b.total]; } } } class ThreadB extends Thread { int total; public void run[] { synchronized[this] { for[int i = 0; i java ParentMain Thread class run[] method will be executed with empty implementation I am in run[] method

Q. What is difference between the Thread class and Runnable interface for creating a Thread?

A thread can be defined in two ways. First, by extending a Thread class that has already implemented a Runnable interface. Second, by directly implementing a Runnable interface.

Difference

THREAD CLASSRUNNABLE INTERFACE
Each thread creates a unique object and gets associated with it. Multiple threads share the same objects.
As each thread create a unique object, more memory required. As multiple threads share the same object less memory is used.
In Java, multiple inheritance not allowed hence, after a class extends Thread class, it can not extend any other class. If a class define thread implementing the Runnable interface it has a chance of extending one class.
A user must extend thread class only if it wants to override the other methods in Thread class. If you only want to specialize run method then implementing Runnable is a better option.
Extending Thread class introduces tight coupling as the class contains code of Thread class and also the job assigned to the thread Implementing Runnable interface introduces loose coupling as the code of Thread is separate form the job of Threads.

Q. What does join[] method?

java.lang.Thread class provides the join[] method which allows one thread to wait until another thread completes its execution.

public class ThreadJoinExample { public static void main[String[] args] { Thread t1 = new Thread[new MyRunnable[], "t1"]; Thread t2 = new Thread[new MyRunnable[], "t2"]; Thread t3 = new Thread[new MyRunnable[], "t3"]; t1.start[]; //start second thread after waiting for 2 seconds or if it's dead try { t1.join[2000]; } catch [InterruptedException e] { e.printStackTrace[]; } t2.start[]; //start third thread only when first thread is dead try { t1.join[]; } catch [InterruptedException e] { e.printStackTrace[]; } t3.start[]; //let all threads finish execution before finishing main thread try { t1.join[]; t2.join[]; t3.join[]; } catch [InterruptedException e] { // TODO Auto-generated catch block e.printStackTrace[]; } System.out.println["All threads are dead, exiting main thread"]; } } class MyRunnable implements Runnable { @Override public void run[] { System.out.println["Thread started: "+Thread.currentThread[].getName[]]; try { Thread.sleep[4000]; } catch [InterruptedException e] { e.printStackTrace[]; } System.out.println["Thread ended: "+Thread.currentThread[].getName[]]; } }

Output

Thread started: t1 Thread started: t2 Thread ended: t1 Thread started: t3 Thread ended: t2 Thread ended: t3 All threads are dead, exiting main thread

Q. What is race-condition?

Race condition in Java occurs in a multi-threaded environment when more than one thread try to access a shared resource [modify, write] at the same time. Since multiple threads try to race each other to finish executing a method thus the name race condition.

Example of race condition in Java

class Counter implements Runnable{ private int c = 0; public void increment[] { try { Thread.sleep[10]; } catch [InterruptedException e] { e.printStackTrace[]; } c++; } public void decrement[] { c--; } public int getValue[] { return c; } @Override public void run[] { //incrementing this.increment[]; System.out.println["Value for Thread After increment " + Thread.currentThread[].getName[] + " " + this.getValue[]]; //decrementing this.decrement[]; System.out.println["Value for Thread at last " + Thread.currentThread[].getName[] + " " + this.getValue[]]; } } public class RaceConditionExample { public static void main[String[] args] { Counter counter = new Counter[]; Thread t1 = new Thread[counter, "Thread-1"]; Thread t2 = new Thread[counter, "Thread-2"]; Thread t3 = new Thread[counter, "Thread-3"]; t1.start[]; t2.start[]; t3.start[]; } }

Output

Value for Thread After increment Thread-2 3 Value for Thread at last Thread-2 2 Value for Thread After increment Thread-1 2 Value for Thread at last Thread-1 1 Value for Thread After increment Thread-3 1 Value for Thread at last Thread-3 0

Using synchronization to avoid race condition in Java
To fix the race condition we need to have a way to restrict resource access to only one thread at a time. We have to use synchronized keyword to synchronize the access to the shared resource.

//This class' shared object will be accessed by threads class Counter implements Runnable{ private int c = 0; public void increment[] { try { Thread.sleep[10]; } catch [InterruptedException e] { e.printStackTrace[]; } c++; } public void decrement[] { c--; } public int getValue[] { return c; } @Override public void run[] { synchronized[this] { // incrementing this.increment[]; System.out.println["Value for Thread After increment " + Thread.currentThread[].getName[] + " " + this.getValue[]]; //decrementing this.decrement[]; System.out.println["Value for Thread at last " + Thread.currentThread[].getName[] + " " + this.getValue[]]; } } } public class RaceConditionExample { public static void main[String[] args] { Counter counter = new Counter[]; Thread t1 = new Thread[counter, "Thread-1"]; Thread t2 = new Thread[counter, "Thread-2"]; Thread t3 = new Thread[counter, "Thread-3"]; t1.start[]; t2.start[]; t3.start[]; } }

Output

Value for Thread After increment Thread-2 1 Value for Thread at last Thread-2 0 Value for Thread After increment Thread-3 1 Value for Thread at last Thread-3 0 Value for Thread After increment Thread-1 1 Value for Thread at last Thread-1 0

Q. What is Lock interface in Java Concurrency API? What is the Difference between ReentrantLock and Synchronized?

A java.util.concurrent.locks.Lock is a thread synchronization mechanism just like synchronized blocks. A Lock is, however, more flexible and more sophisticated than a synchronized block. Since Lock is an interface, you need to use one of its implementations to use a Lock in your applications. ReentrantLock is one such implementation of Lock interface.

Lock lock = new ReentrantLock[]; lock.lock[]; //critical section lock.unlock[];

Difference between Lock Interface and synchronized keyword

  • Having a timeout trying to get access to a synchronized block is not possible. Using Lock.tryLock[long timeout, TimeUnit timeUnit], it is possible.
  • The synchronized block must be fully contained within a single method. A Lock can have it's calls to lock[] and unlock[] in separate methods.

import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConcurrencyLockExample implements Runnable { private Resource resource; private Lock lock; public ConcurrencyLockExample[Resource r] { this.resource = r; this.lock = new ReentrantLock[]; } @Override public void run[] { try { if[lock.tryLock[10, TimeUnit.SECONDS]] { resource.doSomething[]; } } catch [InterruptedException e] { e.printStackTrace[]; } finally { //release lock lock.unlock[]; } resource.doLogging[]; } }

Q. What is the difference between the Runnable and Callable interface?

Runnable and Callable interface both are used in the multithreading environment. Runnable is the core interface provided for representing multi-threaded tasks and Callable is an improved version of Runnable that was added in Java 1.5.

Difference between Callable and Runnable in Java

1. Checked Exception: Callable’s call[] method can throw checked exception while Runnable run[] method can not throw checked exception.

2. Return value: Return type of Runnable run[] method is void , so it can not return any value. while Callable can return the Future object, which represents the life cycle of a task and provides methods to check if the task has been completed or canceled.

3. Implementation: Callable needs to implement call[] method while Runnable needs to implement run[] method.

4. Execution: Limitation of Callable interface lies in java is that one can not pass it to Thread as one pass the Runnable instance. There is no constructor defined in the Thread class which accepts a Callable interface.

Example: Callable Interface

// Java program to illustrate Callable and FutureTask // for random number generation import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; class CallableExample implements Callable { public Object call[] throws Exception { Random generator = new Random[]; Integer randomNumber = generator.nextInt[5]; Thread.sleep[randomNumber * 1000]; return randomNumber; } } public class CallableFutureTest { public static void main[String[] args] throws Exception { // FutureTask is a concrete class that // implements both Runnable and Future FutureTask[] randomNumberTasks = new FutureTask[5]; for [int i = 0; i

Chủ Đề