Posts

Showing posts with the label user defined thread

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

how to create our own thread in java with example

To create user defined thread in java, create a class that extends Thread or implements Runnable interface. Both of the Thread class and Runnable interface are available in java.lang package. class MyClass extends Thread OR class MyClass implements Runnable         •   Now in this class, write a run() method as, public void run (){ statements ; }        by default, this run() method is recognised and executed by a thread when you started a thread.        •    Create an object of MyClass, So that the run() method is available for execution. MyClass obj = new MyClass ();       •    Now, Create a thread and attach the thread to the object obj. Thread t = new Thread ( obj );       •    Run the thread. For this purpose, we should use start() method of Thread class. t ...