Java multithreading is a very good function. Now java can be used in various fields and it is not unrelated to its strength. Today I am in touch with thread synchronization. I will share it with you.
Basically, I feel that everything I learned is used right away. I rarely have the opportunity to take the time to learn something. I am not busy in recent times. I want to finish all my interview questions, there are not many difficulties, but many do not. The problem lies in practice.
Let's get down to the truth. At present, multithreading is purely interest-based learning, and there is no real application scenario. I used to think that java multithreading was messy and many concepts were not quite understandable, but it was clear to write several instances in practice.
The synchronized keyword was mentioned during thread security exercises yesterday. The principle is to lock one or more resources and only allow the current process to use them. I understand that thread synchronization allows various threads to control resource allocation, such as locking resources, releasing resources, and waiting for the release of resources.
The following example shows how to implement it on the Internet. The main idea is to have a plate. Two people operate on the plate. One is responsible for placing the eggs, and the other is only responsible for taking the eggs. When there is chicken in the plate, you cannot put it any more. When the plate is empty, you cannot take the eggs.
The Code is as follows: |
Copy code |
Package threads; Public class TestSynchronous { Public static int size = 50; Public static void main (String [] args) { Plate plate = new Plate (); New Thread1 (plate). start (); New Thread2 (plate). start (); } Public static class Thread1 extends Thread // person in charge of placing eggs { Plate; Public Thread1 (Plate plate) { This. plate = plate; } Public void run () { For (int I = 0; I <size; I ++ ){ Synchronized (plate ){ If (plate. hasEgg ()){ Try { Plate. wait (); } Catch (InterruptedException e ){ E. printStackTrace (); } } Plate. putEgg ("egg "); System. out. println ("put egg ."); Plate. Y (); } } } } Public static class Thread2 extends Thread // take the progress of the eggs { Plate; Public Thread2 (Plate plate) { This. plate = plate; } Public void run () { For (int I = 0; I <size; I ++ ){ Synchronized (plate ){ If (! Plate. hasEgg ()){ Try { Plate. wait (); } Catch (InterruptedException e ){ E. printStackTrace (); } } Plate. eggAway (); System. out. println ("take away egg ."); Plate. Y (); } } } } Public static class Plate // Plate { Object egg; Public Plate () { } Public void putEgg (Object egg) { This. egg = egg; } Public void eggAway () { This. egg = null; } Public boolean hasEgg () { Return egg! = Null; } } } |