Java multi-thread communication-solving security issues, waiting for wake-up mechanism, and java multi-thread

Source: Internet
Author: User

Java multi-thread communication-solving security issues, waiting for wake-up mechanism, and java multi-thread



/*
1. Add a knowledge point
How can a class modify its data together with other classes in all classes?
The Singleton design mode can be used.
Static
You can create a constructor in other classes to accept the same object, so that you can implement the object

2. Select status
The value can be 0 to 1.
You can use bool
Pay attention to the variable range.

3. After synchronization is added, what should I do if it is secure?
Prerequisites! 1. Two or more threads (synchronized) 2. Operate Public Resources 3. Use the same lock
*/

/*
Inter-thread communication:
In fact, multiple threads are operating on the same resource,
However, the operations are different.

*/



/*
1. Why is there a security problem?
The premise is not met.

2. We have not yet understood the nature of the thread
1. the threads compete for the execution right.
2. If the code block is not synchronized, the data will be randomly modified. The data may be modified in half, and the other thread may be modified several times, or even ignore the conditions.
3. even with the synchronous code block, the Code cannot be executed in order, because the first thread will participate in the next competition after execution, with the same probability of competition
Therefore, the synchronization is not synchronized, and wake up is required at this time.
4. In fact, the program is a logic judgment problem, that is, whether there is data
*/


/* Waiting in one of the five States
1. The Thread is inherited from God.
2. This function throws an exception. According to the exception format, try and catch are required.
3. Awakening also inherits from God.
4. You can click the object directly when using it.
5. This makes it easy to differentiate, and also causes the two functions to be written in God. The lock is of any type and any object can be used.

*/
Class Res/* defines a class, which encapsulates data members for calling */
{
String name;
String sex;
Boolean flag = false;/* is used to determine whether the data has been stored. It is encapsulated and easy to use */
}

Class Input implements Runnable
{
Private Res r;
Input (Res r)
{
This. r = r;
}
Public void run ()
{
Int x = 0;
While (true)
{
Synchronized (r)/* can only let one thread in, and the input is advanced, the output is not given, so that the premise is met, there are two threads, the same lock, public resources */
{

If (r. flag)/* true, frozen */
Try {r. wait ();} catch (Exception e) {}/* thread pool. wait for all threads to be in the thread pool. What is wakeup and what is awakened is the thread in the thread pool */
If (x = 0)
{
R. name = "mike";/* value */
R. sex = "man ";
}
Else
{
R. name = "Lili ";
R. sex = "female and female ";
}
X = (x + 1) % 2;/* convert Gender */
R. flag = true;
R. Wake y ();/* wake up when there is a thread. If there is no thread, don't wake up. This is not needed in order. Wake up another thread */
}
}
}
}

Class Output implements Runnable
{
Private Res r;/* object data member */

Output (Res r)
{
This. r = r;/* pass the object in */
}
Public void run ()
{
While (true)
{
Synchronized (r)/* put the object */
{
If (! R. flag)
Try {r. wait ();} catch (Exception e ){}
System. out. println (r. name + "..." + r. sex);/* Delete */
R. flag = false;
R. Y ();/* wake up the input thread */
}
}
}
}


Class InputOutputDemo
{
Public static void main (String [] args)
{
Res r = new Res ();/* The encapsulated class will be passed as a parameter to other classes */

Input in = new Input (r);/* implement multi-threaded class objects */
Output out = new Output (r );

Thread t1 = new Thread (in);/* enable the Thread and put the object implementing the Thread in */
Thread t2 = new Thread (out );

T1.start ();/* enable the thread and call the run function */
T2.start ();
}
}


// Policyall ();

/*
Wait:
Notify ();
Policyall ();

All are used in synchronization because you want to operate on the thread that holds the Monitor (Lock.
Therefore, it must be used in synchronization because only synchronization has a lock.

Why do the methods of these operation threads need to be defined in the Object class?
Because these methods must mark only the locks of the threads they operate during thread operation synchronization,
Only the waiting thread of the same lock can be awakened by notify of the same lock.
It is not allowed to wake up threads in different locks.

That is to say, waiting and waking must be the same lock.

The lock can be any Object, so the method called by any Object can be defined in the Object class.


*/


Code optimization:
/*
Inter-thread communication:
In fact, multiple threads are operating on the same resource,
However, the operations are different.

*/
Class Res
{
Private String name;
Private String sex;
Private boolean flag = false;

Public synchronized void set (String name, String sex)
{
If (flag)
Try {this. wait ();} catch (Exception e) {}/* Remember that the data to be synchronized is the data to be operated together, not the defined data, but the data to be changed */
This. name = name;

This. sex = sex;
Flag = true;
This. Y ();/* this indicates the lock of the synchronous function and the current object */
}
Public synchronized void out ()
{
If (! Flag)
Try {this. wait ();} catch (Exception e ){}
System. out. println (name + "......" + sex );
Flag = false;
This. Policy ();
}
}

Class Input implements Runnable
{
Private Res r;/* used to receive the same object */
Input (Res r)
{
This. r = r;
}
Public void run ()
{
Int x = 0;
While (true)
{
If (x = 0)
R. set ("mike", "man");/* this function is already a synchronous function */
Else
R. set ("Lili", "female and female ");
X = (x + 1) % 2;
}
}
}

Class Output implements Runnable
{
Private Res r;

Output (Res r)
{
This. r = r;
}
Public void run ()
{
While (true)
{
R. out ();/* continuously output */
}
}
}


Class InputOutputDemo2
{
Public static void main (String [] args)
{
Res r = new Res ();

New Thread (new Input (r). start ();/* use all unknown objects and optimize Code */
New Thread (new Output (r). start ();
/*
Input in = new Input (r );
Output out = new Output (r );

Thread t1 = new Thread (in );
Thread t2 = new Thread (out );

T1.start ();
T2.start ();
*/
}
}






Related Article

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.