In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly talks about "the types and differences of Java multithreading". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the types and differences of Java multithreading".
1. Types and differences of multithreading
Thread class, runnable interface, callable interface, when using callable, you need to override the call method, use the FutureTask call, and use the get method to get the return value. The biggest difference between Callable and Thread and Runnable is that Callable can return an asynchronous processing result Future object and throw an exception, while the other two cannot be implemented in runnable with more flexibility and low coupling, so they are more commonly used. Interface-oriented programming is also the core of the six principles of design patterns.
Package thread;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;public class CallableModel implements Callable {@ SuppressWarnings ("unchecked") @ Override public V call () throws Exception {/ / TODO Auto-generated method stub System.out.println ("override call method"); return (V) "call callable with a return value" } public static void main (String [] args) throws InterruptedException, ExecutionException {FutureTask futureTask = new FutureTask (new CallableModel ()); Thread thread = new Thread (futureTask); thread.start (); System.out.println (futureTask.get ());}}
two。 Benefits of multithreading
Give full play to the advantages of multicore CPU, place blocking, facilitate modeling, etc.
The difference between 3.start and run is multithreaded only when you call start. Run is just a normal method, and multiple threads execute synchronously when it is called.
The difference between 3.start and run is multithreaded only when you call start. Run is just a normal method, and multiple threads execute synchronously when it is called.
The difference between 4.runnable and callable callable can be used with Future and FutureTask to obtain the result of asynchronous execution. The call method has a return value, and multithreading is full of unknown. It is very necessary to use futureTask to obtain the execution result. It is necessary to cancel this thread when waiting for a result to be returned for too long.
The difference between 5.CyclicBarrier and CountDownLatch-fence locks are both under java.util.concurrent and can be used to indicate that the code is running to a certain point. CyclicBarrier is used to wait for one set of events to complete, and then start the next event, such as a group of athletes ready to issue a run command. CountDownLatch allows one or more threads to wait for a set of events to occur. 1) after a thread in CyclicBarrier runs to a certain point, the thread stops running until all threads reach this point, while CountDownLatch does not. After a thread runs to a certain point, it just gives a value of-1, and the thread continues to run.
2) CyclicBarrier can only evoke one task, and CountDownLatch can evoke multiple tasks.
3) CyclicBarrier is reusable (by calling the reset method), CountDownLatch is not reusable, and if the count value is 0, the CountDownLatch is no longer available. 6.CyclicBarrier code example
Package thread / * * Project name: test * Class name: ThreadModel * Class description: multithreading through integrated Thread * founder: @ author Wang Fengsheng * creation time: July 1, 2019, 1:00:46 * modifier: @ author Wang Fengsheng * modification time: July 1, 2019, 1:00:46 p.m. * Amendment remarks: * @ version * * / public class ThreadModel extends Thread {private java.util.concurrent.CyclicBarrier cyclicBarrier / * Thread is actually a class that implements the runnable interface. You need to override the run method and call the start method to start * / public ThreadModel (java.util.concurrent.CyclicBarrier cyclicBarrier) {/ / TODO Auto-generated constructor stub this.cyclicBarrier = cyclicBarrier;} @ Override public void run () {/ / TODO Auto-generated method stub super.run () Try {System.out.println (Thread.currentThread (). GetName () + "start waiting"); cyclicBarrier.await (); System.out.println (Thread.currentThread (). GetName () + "start execution"); Thread.sleep (1000 * 2); System.err.println (Thread.currentThread (). GetName () + "execution completed") } catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} public static void main (String [] args) {int threadCount = 3; java.util.concurrent.CyclicBarrier cyclicBarrier = new java.util.concurrent.CyclicBarrier (threadCount); for (int I = 0; I < threadCount) ) {System.out.println ("create worker thread" + I); ThreadModel threadModel = new ThreadModel (cyclicBarrier); threadModel.start ();}
The 7.CountDownlatch code example calls the await method after two threads are started in the main thread, and thread 1 finishes execution. Call countdown, and thread 2 calls countdown after execution, which means that when the thread has finished execution, release the lock of await and continue to execute downwards.
/ * * see the doctor task * Created by jiapeng on 2018-1-7. * / public class SeeDoctorTask implements Runnable {private CountDownLatch countDownLatch; public SeeDoctorTask (CountDownLatch countDownLatch) {this.countDownLatch = countDownLatch;} @ Override public void run () {try {Thread.sleep (3000); System.out.println ("see the doctor successfully, the doctor prescribed some medicine list") } catch (InterruptedException e) {e.printStackTrace ();} finally {if (countDownLatch! = null) {countDownLatch.countDown ();} / * queued tasks * Created by jiapeng on 2018-1-7. * / public class QueueTask implements Runnable {private CountDownLatch countDownLatch Public QueueTask (CountDownLatch countDownLatch) {this.countDownLatch = countDownLatch;} @ Override public void run () {try {Thread.sleep (5000); System.out.println ("queued successfully, you can start to pay");} catch (InterruptedException e) {e.printStackTrace () } finally {if (countDownLatch! = null) {countDownLatch.countDown ();} / * my wife went to see a doctor. When it was my wife's turn to see the doctor * I began to line up to pay the money. * Created by jiapeng on 2018-1-7. * / public class MainClient {public static void main (String [] args) throws Exception {long now = System.currentTimeMillis (); CountDownLatch countDownLatch = new CountDownLatch (2); Executor executor = Executors.newFixedThreadPool (2); executor.execute (new SeeDoctorTask (countDownLatch)); executor.execute (new QueueTask (countDownLatch)); countDownLatch.await () System.out.println ("over, go home cost:" + (System.currentTimeMillis ()-now));}}
The variable modified by the 8.volatile keyword volatile ensures its visibility within the multithread, which is equivalent to a lightweight sychronized, and the variable read by the multithread must be up to date.
9. What is thread-safe multithreaded state and single-threaded state can always get the same result, then it means that it is thread-safe, divided into
10. To get the thread stack dump file deadloop, deadlock, blocking and other problems, you need to print the thread stack. You can use the getStackTrace () method, use jps to get thread pid, use the jstack pid command, or kill-3 pid to get thread stack information.
11. Thread has an exception if an exception occurs and is not caught, the thread terminates, and if the thread holds an object's monitor, the object monitor is immediately released
At this point, I believe you have a deeper understanding of "the types and differences of Java multithreading". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.