In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to use Java multithreading, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
I. concept
1. Process
1.1 process: is an ongoing program, each process execution has an execution order, the order is an execution path, or a control unit.
1.2 Thread: a separate control unit in a process in which a thread controls the execution of a process, and there is at least one thread in a process.
1.3Example java VM:
When Java VM starts, there is a process java.exe, in which at least one thread is responsible for running the java program, and the code that this thread runs exists in the main method, which is called the main thread. Extension: in fact, in more detail, jvm,jvm starts more than one thread, and there are threads responsible for the garbage collection mechanism
two。 The significance of multithreading: improving execution efficiency
Second, the creation of multithreading
1. * created by multithreading, inheriting the Thread class
The purpose of overriding the run method in the Thread class is to store the custom code in the run method and let the thread run
1.2 call the thread's start method, which has two functions: start the thread and call the run method
When multithreading is running, the results are different each time, because multiple threads gain the right to execute cpu, and those who execute cpu will run. To be clear, at a certain time, there can only be one program running. (except for multicore), cpu is switching quickly to achieve what appears to be running at the same time. We can visualize the multi-threaded running behavior in the mutual scramble for the executive power of cpu. This is a feature of multithreading, randomness. Who gets it, who executes it, and as to how long it takes, cpu decides.
Public class Demo extends Thread {public void run () {for (int x = 0; x
< 60; x++) { System.out.println(this.getName()+"demo run---"+x); } } public static void main(String[] args) { Demo d=new Demo();//创建一个线程 d.start();//开启线程,并执行该线程的run方法 d.run(); //仅仅是对象调用方法,而线程创建了但并没有运行 for (int x = 0; x < 60; x++) { System.out.println("Hello World---"+x); } } } 2 创建多线程的第二种方式,步骤: 2.1定义类实现Runnable接口 2.2覆盖Runnable接口中的run方法:将线程要运行的代码存放到run方法中 2.3.通过Thread类建立线程对象 2.4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数 为什么要将Runnable接口的子类对象传递给Thread的构造函数:因为自定义的run方法所属的对象是Runnable接口的子类对象,所以要让线程去执行指定对象的run方法,就必须明确该run方法的所属对象 2.5.调用Thread类的start方法开启线程并调用Runnable接口子类的方法 /* * 需求:简易买票程序,多个窗口同时卖票 */ public class Ticket implements Runnable { private static int tick = 100; Object obj = new Object(); boolean flag=true; public void run() { if(flag){ while (true) { synchronized (Ticket.class) { if (tick >0) {System.out.println (Thread.currentThread (). GetName () + "code:" + tick--);} else {while (true) {show () } public static synchronized void show () {if (tick > 0) {System.out.println (Thread.currentThread (). GetName () + "show:" + tick--);} class ThisLockDemo {public static void main (String [] args) {Ticket t = new Ticket () Thread T1 = new Thread (t); try {Thread.sleep (10);} catch (Exception e) {/ / TODO: handle exception} t.false; Thread T2 = new Thread (t); / / Thread T3 = new Thread (t); / / Thread T3 = new Thread (t); t1.start () T2.start (); / / t3.start (); / / t4.start ();}}
3. What's the difference between implementation and inheritance?
3.1. The implementation method avoids the limitation of single inheritance, and it is recommended to use the implementation method when defining threads.
3.2. Inheriting the Thread class: thread code is stored in the thread subclass run method
3.3. Implement Runnable: thread code is stored in the run method of a subclass of the interface
4. Multithreading-characteristics of run and start
4.1Why override the run method:
The Thread class is used to describe threads, and this class defines a function to store the code that the thread wants to run, which is the run method, that is, the run method in the Thread class, which stores the code that the thread wants to run.
5. Multithreaded running state
Create thread-run-sleep () / wait ()-- freeze-notify ()-Wake up
Create thread-run-stop ()-- die
Create thread-run-did not grab the cpu execution right-temporary freeze
6. Get the thread object and its name
6.1. Each thread has its own default name, with the number starting at 0
6.2.static Thread currentThread (): gets the current thread object
6.3.getName (): get the thread name
6.4. Set the thread name: setName () or use the constructor
Public class Test extends Thread {Test (String name) {super (name);} public void run () {for (int x = 0; x
< 60; x++) { System.out.println((Thread.currentThread()==this)+"..."+this.getName()+" run..."+x); } } } class ThreadTest{ public static void main(String[] args) { Test t1=new Test("one---"); Test t2=new Test("two+++"); t1.start(); t2.start(); t1.run(); t2.run(); for (int x = 0; x < 60; x++) { System.out.println("main----"+x); } } } 三、多线程的安全问题 1.多线程出现安全问题的原因: 1.1.当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行,导致共享数据的错误 1.2.解决办法:对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行 1.3.java对于多线程的安全问题提供了专业的解决方式,就是同步代码块: Synchronized(对象){需要被同步的代码},对象如同锁,持有锁的线程可以在同步中执行,没有持有锁的线程即使获取cpu执行权,也进不去,因为没有获取锁 2.同步的前提: 2.1.必须要有2个或者2个以上线程 2.2.必须是多个线程使用同一个锁 2.3.好处是解决了多线程的安全问题 2.4.弊端是多个线程需要判断锁,较消耗资源 2.5.同步函数 定义同步函数,在方法钱用synchronized修饰即可 /* * 需求: * 银行有一个金库,有两个储户分别存300元,每次存100元,存3次 * 目的:该程序是否有安全问题,如果有,如何解决 * 如何找问题: * 1.明确哪些代码是多线程代码 * 2.明确共享数据 * 3.明确多线程代码中哪些语句是操作共享数据的 */ public class Bank { private int sum; Object obj = new Object(); //定义同步函数,在方法钱用synchronized修饰即可 public synchronized void add(int n) { //synchronized (obj) { sumsum = sum + n; try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("sum=" + sum); //} } } class Cus implements Runnable { private Bank b = new Bank(); public void run() { for (int x = 0; x < 3; x++) { b.add(100); } } } class BankDemo { public static void main(String[] args) { Cus c = new Cus(); Thread t1 = new Thread(c); Thread t2 = new Thread(c); t1.start(); t2.start(); } } 6.同步的锁 6.1函数需要被对象调用,那么函数都有一个所属对象引用,就是this.,所以同步函数使用的锁是this 6.2.静态函数的锁是class对象 静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象,类名.class,该对象的类型是Class 6.3.静态的同步方法,使用的锁是该方法所在类的字节码文件对象,类名.class /* * 需求:简��买票程序,多个窗口同时卖票 */ public class Ticket implements Runnable { private static int tick = 100; Object obj = new Object(); boolean flag=true; public void run() { if(flag){ while (true) { synchronized (Ticket.class) { if (tick >0) {System.out.println (Thread.currentThread (). GetName () + "code:" + tick--);} else {while (true) {show () } public static synchronized void show () {if (tick > 0) {System.out.println (Thread.currentThread (). GetName () + "show:" + tick--);} class ThisLockDemo {public static void main (String [] args) {Ticket t = new Ticket () Thread T1 = new Thread (t); try {Thread.sleep (10);} catch (Exception e) {/ / TODO: handle exception} t.false; Thread T2 = new Thread (t); / / Thread T3 = new Thread (t); / / Thread T3 = new Thread (t); t1.start () T2.start (); / / t3.start (); / / t4.start ();}}
7. Multithreaded, singleton mode-lazy
The difference between lazy and hungry: lazy can delay the loading of instances, if multithreaded access, lazy will have security problems, you can use synchronization, synchronization functions and synchronization code can be used, but it is relatively inefficient. The problem of inefficiency can be solved in the form of double judgment, and the lock used when adding synchronization is the bytecode file object of this kind of lock.
/ * * Singleton mode * / / Hungry Chinese public class Single {private static final Single s=new Single (); private Single () {} public static Single getInstance () {return s;}} / / lazy class Single2 {private static Single2 s2=null Private Single2 () {} public static Single2 getInstance () {if (s2==null) {synchronized (Single2.class) {if (s2==null) {s2=new Single2 ();} return S2 }} class SingleDemo {public static void main (String [] args) {System.out.println ("Hello World");}}
8. Multithreading-deadlock
There will be a deadlock in nested synchronization.
/ * * demand: simple procedure for buying tickets, with multiple windows selling tickets at the same time * / public class DeadTest implements Runnable {private boolean flag; DeadTest (boolean flag) {this.flag = flag;} public void run () {if (flag) {synchronized (MyLock.locka) {System.out.println ("if locka") Synchronized (MyLock.lockb) {System.out.println ("if lockb");} else {synchronized (MyLock.lockb) {System.out.println ("else lockb") Synchronized (MyLock.locka) {System.out.println ("else locka");} class MyLock {static Object locka=new Object (); static Object lockb=new Object ();} class DeadLockDemo {public static void main (String [] args) {Thread T1 = new Thread (new DeadTest (true)) Thread T2 = new Thread (new DeadTest (false)); t1.start (); t2.start ();}} Thank you for reading this article carefully. I hope the article "how to use Java Multithreading" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you 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.