Java Multithreading & Synchronization keywords synchronized & readwritelock read and write files

Source: Internet
Author: User

There are two ways to implement multithreading in Java, one is to inherit the thread class, one to implement the Runnable interface, and the thread class to be defined in the Java.lang package. A class that inherits the thread class to overwrite the run () method in this class can implement multithreaded operations, but only one parent class can inherit from a class, which is the limitation of this method.

1  Public class extends Thread  {2public     void  run () {3          /// thread-executed operation  4        }5 }   

In real-world development, a multithreaded operation rarely uses the thread class, but is accomplished through the Runnable interface.

1  Public class Implements runnable{23    @Override4public     void run () {5         //actions performed by thread 6         }7 }    

Both of these threads are called in the Main method.

1      Public Static voidMain (string[] args) {2Thread actor=NewActor ();3Actor.setname ("Mr.thread");//Thread Threads4 Actor.start ();5         6Thread actressthread=NewThread (NewActress (), "miss.runnable");//Runnable Threads7 Actressthread.start ();8}

The difference between the two ways of implementation and contact:

In the development of the program as long as the multithreading must always be implemented runnable interface mainly, because the implementation of the Runnable interface compared to inherit the thread class has the following advantages:

1, to avoid the limitation of the point inheritance, a class can inherit multiple interfaces.

2, suitable for the sharing of resources

Take the ticket selling procedure as an example, complete by the thread class:

1  Packagemultithreading;2 3  Public classMythreadwithextendsextendsThread {4 5     Private intTickets = 10;6 7 @Override8      Public voidrun () {9 Ten          for(inti = 0; I <= 100; i++) { One             if(tickets>0){ ASystem.out.println (Thread.CurrentThread (). GetName () + "--Sell ticket:" + tickets--); -             } -         } the     } -      -      -      Public Static voidMain (string[] args) { +Mythreadwithextends Thread1 =Newmythreadwithextends (); -Mythreadwithextends thread2 =Newmythreadwithextends (); +Mythreadwithextends thread3 =Newmythreadwithextends (); A  at Thread1.start (); - Thread2.start (); - Thread3.start (); -          -         //each thread is independent and does not share resources, and each thread sells 10 tickets, selling a total of 30. If you do sell tickets, you have a problem.  -     } in  -}

Operation Result:

thread-0--Sell ticket: 10
thread-2--Sell ticket: 10
thread-1--Sell ticket: 10
thread-2--Sell Ticket: 9
thread-0--Sell Ticket: 9
thread-2--Sell ticket: 8
thread-1--Sell Ticket: 9
thread-2--Sell ticket: 7
thread-0--Sell ticket: 8
thread-2--Sell ticket: 6
thread-2--Sell ticket: 5
thread-2--Sell ticket: 4
thread-1--Sell ticket: 8
thread-2--Sell ticket: 3
thread-0--Sell ticket: 7
thread-2--Sell ticket: 2
thread-2--Sell ticket: 1
thread-1--Sell ticket: 7
thread-0--Sell ticket: 6
thread-1--Sell ticket: 6
thread-0--Sell ticket: 5
thread-0--Sell ticket: 4
thread-1--Sell ticket: 5
thread-0--Sell ticket: 3
thread-1--Sell ticket: 4
thread-1--Sell ticket: 3
thread-1--Sell ticket: 2
thread-0--Sell ticket: 2
thread-1--Sell ticket: 1
thread-0--Sell ticket: 1

If you can use runnable to achieve resource sharing, see the example below:

1  Packagemultithreading;2 3  Public classMythreadwithimplementsImplementsRunnable {4 5     Private intTickets = 10;6 7 @Override8      Public voidrun () {9 Ten          for(inti = 0; I <= 100; i++) { One             if(tickets>0){ ASystem.out.println (Thread.CurrentThread (). GetName () + "--Sell ticket:" + tickets--); -             } -         } the     } -      -      -      Public Static voidMain (string[] args) { +Mythreadwithimplements myrunnable =Newmythreadwithimplements (); -Thread Thread1 =NewThread (myrunnable, "window One"); +Thread thread2 =NewThread (myrunnable, "window two"); AThread thread3 =NewThread (myrunnable, "window three"); at  - Thread1.start (); - Thread2.start (); - Thread3.start (); -     } -  in}

Operation Result:

Window two--Sell ticket: 10
Window three--Sell ticket: 9
Window one--Sell ticket: 8
Window three--Sell ticket: 6
Window three--Sell ticket: 4
Window three--Sell ticket: 3
Window three--Sell ticket: 2
Window three--Sell ticket: 1
Window two--Sell ticket: 7
Window one--Sell ticket: 5

Each thread shares the resources of the object myrunnable, the total number of votes sold is right, but the order is chaotic, how to do?

Sync keyword synchronized

When the thread executes, the execution is not ordered. That is, when thread 1 executes, other threads are blocked from executing.

Add Synchronize.

1  PackageMultithreading.sync;2 3  Public classMythreadwithimplementsImplementsRunnable {4 5     Private intTickets = 10;6 7 @Override8      Public synchronized voidrun () {9             //Sync keyword synchronizedTen          for(inti = 0; I <= 100; i++) { One             if(tickets>0){ ASystem.out.println (Thread.CurrentThread (). GetName () + "--Sell ticket:" + tickets--); -             } -         } the     } -      -      -      Public Static voidMain (string[] args) { +          -Mythreadwithimplements myrunnable =Newmythreadwithimplements (); +Thread Thread1 =NewThread (myrunnable, "window One"); AThread thread2 =NewThread (myrunnable, "window two"); atThread thread3 =NewThread (myrunnable, "window three"); -  - Thread1.start (); - Thread2.start (); - Thread3.start (); -     } in  -}

Run results

Window one--Sell ticket: 10
Window one--Sell ticket: 9
Window one--Sell ticket: 8
Window one--Sell ticket: 7
Window one--Sell ticket: 6
Window one--Sell ticket: 5
Window one--Sell ticket: 4
Window one--Sell ticket: 3
Window one--Sell ticket: 2
Window one--Sell ticket: 1

Defects

1. If the thread that acquires the lock is blocked because it waits for IO or other reasons (such as calling the Sleep method), but does not release the lock, the other threads can only wait in a dry way, which affects the execution efficiency of the program.


2, when there are multiple threads read and write files, read and write operations will conflict, write operations will conflict, but read operations will not conflict. But using the Synchronized keyword for synchronization can cause a problem: If multiple threads are simply reading, when a thread is reading, the other thread can only wait for a read operation.


Therefore, a mechanism is needed to enable multiple threads to simply read, and there will be no conflicts between threads, which can be done by lock. Additionally, through lock you can know that the line threads has not been successfully acquired to the lock. This is synchronized can't do. Overall, this means that lock provides more functionality than synchronized.

Readwritelock read-Write file overview

Readwritelock is an interface in which only two methods are defined: A read lock and a write lock.

Read Lock: A thread acquires a read lock, then the B thread can also acquire a read lock.

Write Lock: A thread acquires a write lock, then the B thread cannot get read and cannot acquire a write lock.

1  Public InterfaceReadwritelock {2     /** 3 * Returns The lock used for reading.4 * Read the lock, a thread gets the read lock, then the B thread can also get the read lock5      * @returnThe lock used for reading.6      */  7 Lock Readlock (); 8    9     /** Ten * Returns The lock used for writing. One * Write the lock, a thread acquires a write lock, then the B thread cannot get read and cannot acquire a write lock.  A      * @returnThe lock used for writing. -      */   - Lock Writelock ();  the}

。。。 Not to be continued

Java Multithreading & Synchronization keywords synchronized & readwritelock read and write files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.