In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
The main content of this article is "how to learn Java multithreading". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to learn Java multithreading.
Catalogue
Multitasking, multithreading
Programs, processes, threads
Learn to read jdk documents
Creation of threads
1. Inherit the Thread class
two。 Implement the Runable interface
Understand concurrency scenarios
Scene of race between tortoise and hare
Implement the callable interface
Understand functional interface
Understand the state of a thread
Thread stop
Thread hibernation sleep
1. Network delay
two。 Countdown, etc.
Thread courtesy yield
Thread enforcement
Observe thread status
Priority of the thread
Daemon thread
Thread synchronization mechanism
1.synchronized synchronization method
two。 Sync block synchronized (Obj) {}
Lock
Synchronized and lock
Multitasking, multithreading
In a multitasking scenario, two things seem to be doing at the same time, but in fact, your brain is only doing one thing at a time, and the interval may be very small, but it seems to make you feel like you are doing both at the same time.
Considering the blocking problem, the multithreaded scenario and multithreaded concurrent scenario are introduced.
Programs, processes, threads
Program = instruction + data (static)
The program running in the operating system is a process, and a process can have multiple threads.
For example, listening to sound, watching images, watching on-screen comments when watching videos, etc.
Learn to read jdk documents
For example, if you want to see Thread,
You can search and read.
If you turn down, you will see:
Thread creation 1. Inherit the Thread class / / create threads 1: inherit the Thread class, override the run method, call the start () method to open the thread public class TestThread1 extends Thread {@ Override public void run () {/ / run () method body IntStream.range (0Jing 20) .forEach (I-> {System.out.println ("I'm looking at the code" + I);}) } public static void main (String [] args) {/ / create a thread object TestThread1 testThread1=new TestThread1 (); / / call the start () method to start the thread, which may not be executed immediately. TestThread1.start () is scheduled by cpu. / / main method main method IntStream.range (0Power20) .forEach (I-> {System.out.println ("I am learning multithreading" + I);});}}
A little exercise:
/ practice thread implementation to download pictures synchronously to threads public class TestThread2 extends Thread {private String url; private String name; public TestThread2 (String url, String name) {this.url = url; this.name = name;} @ Override public void run () {WebDownload webDownload=new WebDownload (); webDownload.downloader (url,name); System.out.println ("downloaded file name:" + name) } public static void main (String [] args) {TestThread2 t1=new TestThread2 ("https://profile.csdnimg.cn/B/D/2/3_sxh06","1.jpg"); TestThread2 t2=new TestThread2 (" https://profile.csdnimg.cn/B/D/2/3_sxh06","2.jpg"); TestThread2 t3=new TestThread2 ("https://profile.csdnimg.cn/B/D/2/3_sxh06","3.jpg");") T1.start (); t2.start (); t3.start ();}} / / downloader class WebDownload {/ / download method public void downloader (String url,String name) {try {FileUtils.copyURLToFile (new URL (url), new File (name));} catch (IOException e) {e.printStackTrace () System.out.println ("IO exception, downloader method error");}} 2. Method 2 to implement the Runable interface / / create threads: implement the Runable interface public class TestThread3 implements Runnable {@ Override public void run () {/ / run () method thread body IntStream.range (0recover20) .forEach (I-> {System.out.println ("I'm looking at the code" + I);}) } public static void main (String [] args) {/ / create a thread object TestThread3 testThread3=new TestThread3 (); / / call the start () method to start the thread, which may not be executed immediately, and the cpu schedules execution / / Thread thread=new Thread (testThread3); / / thread.start (); / / or the abbreviation new Thread (testThread3) .start () / / main method main method IntStream.range (0100) .forEach (I-> {System.out.println ("I am learning multithreading" + I);});}}
Understand concurrency scenarios
Problems arise when multiple threads use the same resource. Take a look at the following example of buying a train ticket:
Public class TestThread4 implements Runnable {/ / votes private int ticketNums=10; @ Override public void run () {while (true) {if (ticketNums= 100) {winner=Thread.currentThread () .getName (); System.out.println ("winner:" + winner); return true;} else {return false }} public static void main (String [] args) {Race race=new Race (); new Thread (race, "rabbit"). Start (); new Thread (race, "tortoise"). Start ();}} implement callable interface / / thread creation method 3public class TestCallable implements Callable {private String url; private String name; public TestCallable (String url, String name) {this.url = url This.name = name;} @ Override public Boolean call () {com.sxh.thread.WebDownload webDownload=new com.sxh.thread.WebDownload (); webDownload.downloader (url,name); System.out.println ("downloaded file name:" + name); return true } public static void main (String [] args) throws ExecutionException, InterruptedException {TestCallable t1=new TestCallable ("https://profile.csdnimg.cn/B/D/2/3_sxh06","1.jpg"); TestCallable t2=new TestCallable (" https://profile.csdnimg.cn/B/D/2/3_sxh06","2.jpg"); TestCallable t3=new TestCallable ("https://profile.csdnimg.cn/B/D/2/3_sxh06","3.jpg");)" / / create execution service ExecutorService ser= Executors.newFixedThreadPool (3); / / submit execution Future r1=ser.submit (T1); Future r2=ser.submit (T2); Future r3=ser.submit (T3); / / get result boolean rs1=r1.get (); boolean rs2=r2.get (); boolean rs3=r3.get () / / disable the service ser.shutdownNow ();}} understand the functional interface
Any interface contains only one abstract method, which is a functional interface.
/ * Development of lambdab expressions * / public class TestLambda1 {/ / 3. Static inner class static class Like2 implements ILike {@ Override public void lambda () {System.out.println ("I like lambda2");}} public static void main (String [] args) {ILike like=new Like (); like.lambda (); like=new Like2 (); like.lambda (); / / 4. Local inner class class Like3 implements ILike {@ Override public void lambda () {System.out.println ("I like lambda3");}} like=new Like3 (); like.lambda (); / / 5. Anonymous inner class like=new ILike () {@ Override public void lambda () {System.out.println ("I like lambda4");}}; like.lambda (); / / 6. Simplify like= ()-> {System.out.println ("I like lambda5");}; like.lambda ();} / / 1 with lambda. Define a functional interface interface ILike {void lambda ();} / / 2. The implementation class class Like implements ILike {@ Override public void lambda () {System.out.println ("i like lambda");}} understands the state of the thread
Thread stops public class TestStop implements Runnable {/ / 1. Set a flag bit private boolean flag=true; @ Override public void run () {int iTuno; while (flag) {System.out.println ("run...thread.." + iTunes +);}} / / 2. Set an exposed method to stop the thread, converting the flag bit public void stop () {this.flag=false;} public static void main (String [] args) {TestStop stop=new TestStop (); new Thread (stop) .start (); for (int I = 0; I)
< 1000; i++) { System.out.println("main"+i); if (i==900){ //调用stop方法,让线程停止 stop.stop(); System.out.println("线程该停止了"); } }// IntStream.range(0,1000).forEach(i->{/});}} Thread hibernate sleep
Every object has a lock, and sleep will not release the lock
1. Network delay / / simulated delay try {Thread.sleep; / / ms} catch (InterruptedException e) {e.printStackTrace ();} 2. Countdown to public static void main (String [] args) {try {tendown ();} catch (InterruptedException e) {e.printStackTrace ();}} public static void tendown () throws InterruptedException {int num=10; while (true) {Thread.sleep (1000); System.out.println (num--) If (num {for (int I = 0; I)
< 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("//"); }); //观察状态 Thread.State state=thread.getState(); System.out.println(state); //NEW //启动后 thread.start(); state=thread.getState(); System.out.println(state); //Run while (state != Thread.State.TERMINATED) { Thread.sleep(100); state=thread.getState();//更新线程状态 System.out.println(state); //Run } }}线程的优先级//测试线程的优先级public class TestPriority { public static void main(String[] args) { //主线程默认优先级 System.out.println(Thread.currentThread().getName()+"--->"+ Thread.currentThread () .getPriority (); MyPriority myPriority=new MyPriority (); Thread t1=new Thread (myPriority); Thread t2=new Thread (myPriority); Thread t3=new Thread (myPriority); Thread t4=new Thread (myPriority); Thread t5=new Thread (myPriority); Thread t6=new Thread (myPriority); / / set priority before starting t1.start (); t2.setPriority (1) T2.start (); t3.setPriority (4); t3.start (); t4.setPriority (Thread.MAX_PRIORITY); t4.start (); t5.setPriority (- 1); t5.start (); t6.setPriority (11); t6.start () }} class MyPriority implements Runnable {@ Override public void run () {System.out.println (Thread.currentThread () .getName () + "-->" + Thread.currentThread () .getPriority ());}} daemon thread
Threads are divided into user threads and daemon threads
/ / Test daemon thread public class TestDaemon {public static void main (String [] args) {God god=new God (); You you=new You (); Thread thread=new Thread (god); thread.setDaemon (true); / / default is false for user thread thread.start (); new Thread (you) .start () }} class God implements Runnable {@ Override public void run () {while (true) {System.out.println ("God bless you");}} class You implements Runnable {@ Override public void run () {for (int I = 0; I)
< 36000; i++) { System.out.println("你活着"+i); } System.out.println("goodbye!!"); }}线程同步机制 解决安全性问题:队列+锁 1.synchronized 同步方法 默认锁的是this,如需锁其他的,使用下面的同步块 //synchronized 同步方法 private synchronized void buy(){ if (ticketNums{ synchronized (list){ list.add(Thread.currentThread().getName()); } }).start(); } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); }}lockclass A{ //ReentrantLock 可重入锁 private final ReentrantLock lock=new ReentrantLock(); public void f(){ lock.lock();//加锁 try{ //..... } finally{ lock.unlock();//释放锁 } } }synchronized与lock lock是显示锁需要手动开关,synchronized是隐式锁,出了作用域自动释放 lock只有代码块锁,synchronized有代码块锁和方法锁 JVM将花费更少的时间来调度线程,性能更好,更有扩展性 优先使用:Lock>Synchronization code block > synchronization method
At this point, I believe you have a deeper understanding of "how to learn 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.