In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how java uses two threads to write a file at the same time". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Multithreading
A thread is the smallest unit of a program's execution flow. It is an entity in a process, and it is the basic unit that is independently dispatched and dispatched by the system. The thread itself does not own system resources, but only has a little bit of essential resources in running. But it can share all the resources owned by the process with other threads that belong to the same process. One thread can create and undo another thread, and multiple threads in the same process can execute concurrently. Due to the mutual restriction between threads, threads are intermittent in operation. Threads also have three basic states: ready, blocked, and running. The ready state means that the thread has all the conditions to run and can logically run and wait for the processor; the running state means that the thread occupies the processor is running; the blocking state means that the thread is waiting for an event (such as a semaphore). Logically unexecutable. Every program has at least one thread, and if the program has only one thread, it is the program itself.
The meaning of multithreading is to make an application have multiple execution paths, so as to improve the execution efficiency of the process (program).
Multithreading in 2.JAVA
2.1 Overview of implementation
There are three ways for JAVA to implement multithreading: 1) inheriting Thread to implement multithreading. 2) multithreading is realized by implementing Runnable interface. 3) use ExecutorService, Callable and Future to implement multithreading with returned results. The specific implementation of these three methods, do not repeat one by one here, there are a lot of relevant blogs on the Internet, friends who do not understand can go to see.
The JAVA program runs on the principle that commands to start JVM,JVM will start a process, which will start a main thread. However, the startup of JVM must also be multithreaded, and in general, at least two threads are started: the main thread and the garbage collection thread.
2.2 Thread Life cycle
1) New 2) ready 3) run 4) Block 5) Dead
2.3 priority of the thread
There are two ways to schedule threads: 1) time-sharing scheduling. 2) preemptive scheduling. JAVA uses the latter, and by default, threads preempt resources (CPU execution rights). We can set the priority of the thread through the setPriority method, which defaults to 5 and ranges from 1 to 10. But in general, just setting the priority of the thread cannot make the thread execute orderly and efficiently, so we need to learn more methods and mechanisms.
2.4 Thread control (common methods)
1) dormant thread 2) join thread 3) comity thread 4) background thread 5) terminate thread
2.5 Safety issues of multithreading
In a multithreaded environment, most of the time, the data will be shared, and there are multiple statements to operate the shared data, so dirty data will often appear. So in order to solve the problem of thread safety, we can achieve our goal through the synchronized synchronous lock object.
1) synchronize the code block
Synchronized (object) {code block that needs to be synchronized}
2) synchronization method
Add synchronization to the method, where the lock object is this.
3) static synchronization method
Add synchronization to the method. The lock here is the bytecode file of the current class.
PS:JDK5 's subsequent locking and releasing operations for threads: Lock locks.
3. Write a file with multiple threads
How to achieve multithreading or reading or writing a file at the same time? As we all know, a file can only be read (written) by one thread at a time. If two threads are required to write a file at the same time, how to allocate this critical resource effectively and orderly?
Below I will use an example to illustrate my solution-the sleep awakening mechanism.
Requirements: two threads write a TXT file, thread 1 2:so do I love you thread. Ensure that threads 1 and 2 execute in an orderly manner, with an I love you sentence corresponding to a so do I sentence.
The first step is to create the WRFile class. This step is crucial.
Package cn.Thread.love; import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile; public class WRFile {/ / String str; boolean flag; public WRFile () {} public synchronized void read1 () {if (this.flag) {try {this.wait ();} catch (InterruptedException e) {e.printStackTrace ();}} RandomAccessFile ra = null; try {ra = new RandomAccessFile ("love.txt", "rw"); ra.seek (ra.length ()) Ra.writeBytes ("I love you"); ra.writeBytes ("\ r\ n");} catch (Exception e) {e.printStackTrace ();} finally {try {ra.close ();} catch (IOException e) {e.printStackTrace ();}} / / modify the tag to wake up thread this.flag = true; this.notify ();} public synchronized void read2 () {if (! this.flag) {try {this.wait () } catch (InterruptedException e) {e.printStackTrace ();}} RandomAccessFile ra = null; try {ra = new RandomAccessFile ("love.txt", "rw"); ra.seek (ra.length ()); ra.writeBytes ("so do I"); ra.writeBytes ("\ r\ n");} catch (Exception e) {e.printStackTrace ();} finally {try {ra.close ();} catch (IOException e) {e.printStackTrace () }} / / modify tag to wake up thread this.flag = false; this.notify ();}}
The second step is to create our two thread classes, the first FirstThread.
Package cn.Thread.love; public class FirstThread implements Runnable {private WRFile wr = new WRFile (); public FirstThread (WRFile wr) {this.wr = wr;} @ Override public void run () {while (true) {wr.read1 ();}
Second SecondThread
Package cn.Thread.love; public class SecondThrad implements Runnable {private WRFile wr = new WRFile (); public SecondThrad (WRFile wr) {this.wr = wr;} @ Override public void run () {while (true) {wr.read2 ();}
The third step is that the main method starts the thread
Package cn.Thread.love; public class LoveDemo {public static void main (String [] args) {/ / create data object WRFile wr = new WRFile (); / / set and get class FirstThread ft = new FirstThread (wr); SecondThrad st = new SecondThrad (wr); / / thread class Thread th2 = new Thread (ft); Thread th3 = new Thread (st); / / start thread th2.start (); th3.start ();}}
Can achieve two threads at the same time (orderly) write a file, more than two, or other operations can also refer to this idea to achieve.
This is the end of the content of "how to write a file with two threads in java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.