JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Showing posts with label core java interview question answer. Show all posts
Showing posts with label core java interview question answer. Show all posts

How to stop a thread in Java with Example

12:47 AM
It's easy to start a thread in Java because you have a  start()  method but it's difficult to stop the thread because there is no working stop() method. Well, there was a  stop()  method in Thread class, when Java was first released but that was deprecated later. In today's Java version, You can stop a thread by using a  boolean volatile variable .   If you remember, threads in Java start execution from  run()  method and stop, when it comes out of run() method, either normally or due to any exception. You can leverage this property to stop the thread. All you need to do is create a boolean variable e.g.  Exit  or  Stop . Your thread should check its value every iteration and comes out of the loop and subsequently from  run()  method if  Exit  is true.   In order to stop the thread, you need to  set the value of this boolean variable to true when you want to stop a running thread. Since you are setting this variable from a different thread e.g. main thread, it's i

Difference between Thread.start() and Thread.run() method in Java?

11:25 PM
A thread is started in Java by calling the start() method of java.lang.Thread class, but if you learn more you will find out that start() method internally calls the run() method of Runnable interface to execute the code specified in the run() method in a separate thread. Now the question comes, why can't you just call the run() method instead of calling the start() method? Since start() is calling the run() anyway, calling run directly should have the same effect as calling the start, no? when you directly call the run() method then the code inside run() method is executed in the same thread which calls the run method. JVM will not create a new thread until you call the start method. when you call the Thread.start() method, then the code inside run() method will be executed on a new thread, which is actually created by the start() method Another key difference between start and run method to remember is that you can call the run method multiple time, JVM will not th

.