In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces Java how to achieve multithreading, thread synchronization related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this Java how to achieve multithreading, thread synchronization article will have a harvest, let's take a look.
1 multithreaded 1.1 process
Process: is a running program
It is an independent unit for the system to allocate and invoke resources.
Each process has its own memory space and system resources.
Three characteristics of the process
Independence: processes are independent of each other and have their own independent memory areas.
Dynamic: a process is a running program that dynamically takes up memory, CPU, network and other resources.
Concurrency: CPU will time-sharing polling switching to serve each process in turn, because the switching speed is so fast that it makes us feel as if we are executing at the same time, which is concurrency (concurrency: multiple processes are executed at the same time)
1.2 Thread
Thread: is a single sequential control flow in a process and is an execution path
Single thread: a process has only one execution path
Multithreading: a process has multiple execution paths
1.3Multithreading implementation 1.3.1 method 1: inherit Tread class
Process:
1. Define a MyTread class that inherits the Tread class
2. Override run () method in the MyTread class
3. Create an object of the MyTread class
4. Start the thread: void start ()
Why override the run () method?
Because run () is used to encapsulate the code executed by the thread
What is the difference between run () method and start () method?
Run (): code executed by the wrapper thread, called directly, equivalent to a call to a normal method
Start (): starts the thread, and then calls the run () method in this thread by JVM
Example
MyTread class:
Package test;//1, define a class of MyTread inheriting Tread class public class MyThread extends Thread {2, override the run () method @ Override public void run () {for (int item0 / Thread.sleep) {/ / try {/ / Thread.sleep (100) in the MyTread class; / /} catch (InterruptedException e) {/ / e.printStackTrace () / /} / / System.out.println (Thread.currentThread (). GetName () + "for sale" + tickets + "ticket"); / / tickets--; / / tickets=99//} / /} private static synchronized void sellTicket () {if (tickets > 0) {try {Thread.sleep (100) } catch (InterruptedException e) {e.printStackTrace ();} System.out.println (Thread.currentThread (). GetName () + "being sold" + tickets + "ticket"); tickets--; / / tickets=99}} 1.11Thread-safe classes (see)
The methods in the source code are all modified by synchronized
StringBuffer
Thread-safe, variable character sequence
Starting with version JDK 5, it was replaced by StringBuilder. You should usually use the StringBuilder class because it supports all the same operations, but it is faster because it does not perform synchronization
Vector
Starting with the Java 2 platform v1.2, this class improves the List interface to make it a member of Java Collections Framework. Unlike the new collection implementation, Vector is synchronized. If you do not need a thread-safe implementation, it is recommended to use ArrayList instead of Vector
Hashtable
This class implements a hash table that maps keys to values. Any non-null object can be used as a key or value
Starting with the Java 2 platform v1.2, this class has been improved to implement the Map interface, making it a member of Java Collections Framework. Unlike the new collection implementation, Hashtable is synchronized. If you do not need a thread-safe implementation, it is recommended to use HashMap instead of Hashtable
Static List snchronizedList (List list) in the Collections class: returns a list of synchronization (thread safety) supported by the specified list
Package test;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;public class Demo {public static void main (String [] args) {/ / static List snchronizedList (List list): returns a list of synchronization (thread safety) supported by the specified list Collection list = Collections.synchronizedList (new ArrayList ()); / * the source code returns Synchronized public static List synchronizedList (List list) {return (list instanceof RandomAccess? New Collections.SynchronizedRandomAccessList (list): new Collections.SynchronizedList (list));} * /} 1.12Lock lock
Lock is an interface that cannot be instantiated directly, so it is instantiated using the implementation class ReentrantLock (after JDK5)
ReentrantLock construction method:
The method name indicates that ReentrantLock () creates an instance object of ReentrantLock
The method of acquiring and releasing locks in Lock:
The method name indicates that void lock () acquires the lock void unlock () releases the lock
It is recommended to use try {} finall {} code blocks to lock and release locks
Package test;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class SellTicket implements Runnable {private static int tickets = 100; private Lock lock = new ReentrantLock (); @ Override public void run () {while (true) {try {lock.lock () If (tickets > 0) {try {Thread.sleep (100);} catch (InterruptedException e) {e.printStackTrace () } System.out.println (Thread.currentThread (). GetName () + "being sold" + tickets + "ticket"); tickets--;}} finally {lock.unlock ();} 1.13 thread communication
Thread communication must be when multiple threads are operating the same resource in order to communicate.
The method name indicates that public void wait () puts the current thread into a waiting state. This method must call public void notify () to wake up a thread in the waiting state on the current lock object. This method must call public void notifyAll () to wake up all threads in the waiting state on the current lock object. This method must call 1.14 producer consumer 1.14.1 producer consumer overview.
In order to reflect the waiting and awakening in the process of production and consumption, Java provides several methods for us to use, which are in the Object class.
Wait and Wake up methods of Object Class
The method name indicates that void wait () causes the current thread to wait until another thread calls the object's notify () method or notifyAll () method void notify () wakes up a single thread waiting for the object monitor void notifyAll () wakes up all threads waiting for the object monitor 1.14.2 producer consumer case
Milk box class
Package test;//1: define the milk box class public class Box {/ / define a member variable to represent the x bottle of milk private int milk; / / define a member variable to represent the state of the milk box private boolean state = false / / provide the operation of storing and obtaining milk public synchronized void put (int milk) {/ / if there is milk waiting for consumption if (state) {try {wait ();} catch (InterruptedException e) {e.printStackTrace () }} / / if there is no milk, produce milk this.milk = milk; System.out.println ("the milkman will put the milk in the milk box" + this.milk + "bottle milk"); / / after the production is finished, modify the status of the milk box state = true; / / wake up other waiting threads notifyAll () } public synchronized void get () {/ / if there is no milk, wait until if (! state) {try {wait ();} catch (InterruptedException e) {e.printStackTrace () }} / / if there is milk, consume milk System.out.println ("user gets first" + this.milk + "bottle milk"); / / after consumption, modify the milk box status state = false; / / wake up other waiting threads notifyAll ();}}
Producer class
Package test;//2: producer class (Producer): implement the Runnable interface public class Producer implements Runnable {private Box b; public Producer (Box b) {this.b = b;} / / override the run () method, and call the operation @ Override public void run () {for (int I = 1; I) for storing milk.
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.