How do you handle multi-threading in Java? What Interfaces are used? How do you create new thread?
Anonymous
In Java, we use Synchronization (synchronized keyword) to handle multi threading. Creating a thread: There are two ways: 1) Extend the Thread class: class MyThread extends Thread{ public void run(){ //code for what the thread needs to do} } 2) Implement the Runnable Interface: class MyRunnable implements Runnable{ public void run(){ //code for what the thread needs to do} } Since Java does not support inheritance of multiple classes, using first method to implement threads inhibits MyThread class from inheriting any other class, hence the second method is preferable. Then, in the class where you are creating instance of the thread, //method 1: class TestThreads{ public static void main(String[] args){ Thread t1 = new Thread(); Thread t2 = new Thread(); t1.start(); t2.start(); }} //method 2: class TestThreads{ public static void main(String[] args){ MyRunnable mr = new MyRunnable(); Thread t1 = new Thread(mr); Thread t2 = new Thread(mr); t1.start(); t2.start(); }} Note that in the second method, only one instance of the MyRunnable class is created and can be passed as a parameter to create multiple threads. The call of start() method on a thread calls the run() method and executes the code in it, once the run method terminates, the thread dies. The most important idea is that once a thread is started, a fresh Stack begins.
Check out your Company Bowl for anonymous work chats.