This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Q: What is the difference between implementing Runable and continuing Thread in Java?
Since I started using threads in Java, I’ve found two ways to write threads:
And implements Runnable: public class MyRunnable implements Runnable { public void run() { //Code } } //Started with a "new Thread(new MyRunnable()).start()" callCopy the code
Alternatively, use extends Thread:
public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
//Started with a "new MyThread().start()" call
Copy the code
Are there any significant differences between the two code blocks?
Answer:
Only inherit if you want to override some behavior.
Rather, it should be understood as:
Less inheritance, more interfaces.
Answer:
In general, I recommend that you use Runnable instead of something like Thread because it keeps your work loosely tied to concurrent choices. For example, if you use aRunnable and later decide that you don’t really need its Thread, you can just call threada.run ().
Warning: I strongly recommend not using raw threads here. I prefer to use Callables and FutureTasks (from Javadoc: “Cancelling asynchronous computation”). The integration of timeouts, proper cancellation, and thread pools supported by modern concurrency are all more useful to me than a large number of primitive threads.
Follow-up: There’s a FutureTask constructor that lets you use Runnables (if you’re most comfortable with it) and still benefit from modern concurrency tools. Refer to the javadoc:
If you don’t need a specific result, consider using a construct of the following form:
Future<? > f = new FutureTask<Object>(runnable, null)Copy the code
Therefore, if we replace them with runnable your, threadA gets the following information:
new FutureTask<Object>(threadA, null)
Copy the code
Another option that allows you to get closer to Runnables is ThreadPoolExecutor. You can use the execute method to pass in Runnable to perform a given task at some future time.
If you want to try to use the thread pool, then the above code snippet into the following content (using the Executors. NewCachedThreadPool factory () method) :
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new ThreadA());
Copy the code
The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 5…
The authors suggest: Just take a look. Creating thread pools and asynchronous tasks is common
Thank you for reading this, if this article is well written and if you feel there is something to it
Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!
If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️