Dark Horse programmer-Java basics-multi-thread Communication

Source: Internet
Author: User

Inter-thread communication:In fact, multiple threads operate on the same resource, but 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 (R. Flag)

Try {R. Wait ();} catch (exception e ){}

This. Name = Name;

This. Sex = sex;

Flag = true;

This. Policy ();

}

Public synchronized void out ()

{

If (R. Flag)

Try {R. Wait ();} catch (exception e ){}

System. Out. println (name + "......" + sex );

Flag = false;

This. Policy ();

}

}

Class input implements runnable {

Private res R;

Input (res r ){

This. r = R;

}

Public void run (){

Int x = 0;

While (true ){

If (x = 0)

R. Set ("Mike", "man ");

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 ();

}

}

}

Class inputoutputdemo {

Public static void main (string [] ARGs ){

Res r = new res ();

New thread (new input (R). Start ();

New thread (new output (R). Start ();

}

}

Wait (); y (); notifyall (); are used in synchronization because you need 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 on during thread operation synchronization, and only the waiting threads of the same lock can

Same lockUpperNotify wake up. 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 can be called by any object.

YiObject Class.

........................................ .......................................

Examples of producers and consumers

For multiple producers and consumers. Why define the while judgment mark. Cause: Let the wake-up thread judge again.

Why does it define policyall, because it is necessary to wake up the thread of the other party. Because only ipvy is used, it is easy to wake up only local threads. CauseProgramAll threads in.

Class producerconsumerdemo {

Public static void main (string [] ARGs ){

Resource r = new resource ();

Producer pro = new producer (R );

Consumer con = new consumer (R );

Thread T1 = new thread (Pro );

Thread t2 = new thread (Pro );

Thread T3 = new thread (CON );

Thread t4 = new thread (CON );

T1.start ();

T2.start ();

T3.start ();

T4.start ();

}

}

Class resource {

Private string name;

Private int COUNT = 1;

Private Boolean flag = false;

Public synchronized void set (string name ){

While (FLAG)

Try {This. Wait ();} catch (exception e ){}

// T1 (disqualified) T2 (eligible)

This. Name = Name + "" + Count ++;

System. Out. println (thread. currentthread (). getname () + "... producer..." + this. Name );

Flag = true;

Condition_con.signal (); // you can avoid waking up when specified, so that signalall () is not needed ();And policyall (); (already replaced)

}

Finally {

Lock. Unlock ();// The lock release action must be performed.

}

}

// T3 T4

Public void out ()Throws interruptedexception{

Lock. Lock ();

Try {

While (! Flag)

Condition_con. Await (); 1.5 New Feature: you can wait for the value by specifying it,Replaced by wait ();

System. Out. println (thread. currentthread (). getname () + "... consumer ......" + this. Name );

Flag = false;

Condition_ Pro. Signal (); // you can avoid waking up when specified, so you do not need signalall ();And policyall (); (already replaced)

}

Finally {

Lock. Unlock ();

}

}

}

Class producerImplements runnable{

Private resource res;

Producer (resource res ){

This. Res = res;

}

Public void run (){

While (true ){

Try {

Res. Set ("+ product + ");

}Catch (interruptedexception e ){}

}

}

}

Class consumerImplements Runnable{

Private resource res;

Consumer (resource res ){

This. Res = res;

}

Public void run (){

While (true ){

Try {

Res. Out ();

}Catch (interruptedexception e ){}

}

}

}

JDK provides a multi-thread upgrade solution. Replace synchronized with the actual lock operation. Replace the condition object with the wait, policy policyall, In the object. This object can be

Lock. In this example, only the other party is awakened.

Stop thread:

How to stop a thread? : The run method ends. Enable multi-thread running and runningCodeIt is usually a loop structure. As long as the loop is controlled, the run method can end, that is, the thread end.

Special case: When the thread is frozen. The tag is not read. The thread will not end.

When there is no specified method to restore the frozen thread to the running state, clear the frozen thread. Force the thread to return to the running state. In this way, the operation mark can end the thread. Thread

Class provides this method interrupt ();

 

Class stopthread implements runnable {

Private Boolean flag = true;

PublicSynchronizedeVoid run (){

While (FLAG){// Set flag to false to control the loop.

Try {

Wait ();

}

Catch (interruppedexception E)

{

System. Out. println (thread. currentthread (). getname () + "... exception ");

Flag = false; // Replace the following changeflag ();

}

System. Out. println (thread. currentthread (). getname () + "... Run ");

}

}

Public void changeflag (){

Flag = false;

}

}

Class stopthreaddemo {

Public static void main (string [] ARGs ){

Stopthread ST = new stopthread ();

Thread T1 = new thread (ST );

Thread t2 = new thread (ST );

T1.setdaemon (true); // The daemon thread. To be called before the thread is online, the daemon thread automatically ends when the foreground thread ends, and the blue font is removed.

T2.setdaemon (true );

T1.start ();

T2.start ();

Int num = 0;

While (true ){

If (Num ++ = 60 ){

St. changeflag ();

// T1.interrupt (); // clear the freeze. Force the thread back to the running state

// T2.interrupt (); 

Break;

}

System. Out. println (thread. currentthread (). getname () + "......" + num );

}

System. Out. println ("over ");

}

}

........................................ ......................................

Join: When thread a executes the. Join () method of thread B, thread a waits. A will only execute after all thread B is executed. Join can be used to temporarily join a thread for execution.

Class demo implements runnable {

Public void run (){

For (INT x = 0; x <70; X ++ ){

System. Out. println (thread. currentthread (). tostring () + "..." + x );

Thread. Yield ();

}

}

}

Class joindemo {

Public static void main (string [] ARGs) throws exception {

Demo d = new demo ();

Thread T1 = new thread (d );

Thread t2 = new thread (d );

T1.start ();

// T1.setpriority (thread. max_priority );

T2.start ();

// T1.join ();

For (INT x = 0; x <80; X ++ ){

// System. Out. println ("Main..." + x );

}

System. Out. println ("over ");

}

}

........................................ .....................................

Class mythread extends thread {

Public void run (){

Try {

Thread. currentthread (). Sleep (3000 );

} Catch (interruptedexception e ){}

System. Out. println ("mythread running ");

}

}

Public class threadtest {

Public static void main (string argv []) {

Mythread T = new mythread ();

T. Run ();

T. Start ();

System. Out. println ("thread test ");

}

}

Code analysis process:

Mythread T = new mythread (); creates a thread.

T. Run ();

Call the run method of the mythread object. This means that only one thread is running and the main thread is running. When the main thread executes sleep (3000); In the run method. This is when the main thread is frozen. The program does not have any

Run. After 3 seconds, the main thread prints the mythread running. The run method execution is complete.

T. Start ();

The T thread is enabled. There are two possible cases. First, after the main thread only executes T. Start (), it also has the execution right to continue the execution and print the thread test. The main thread ends. T thread to obtain execution right, call

Your own run method. Then run the sleep (3000); freeze for 3 seconds. 3 seconds later, the print mythread running t thread ends, and the entire program ends.

The second case: the main thread executes to T. Start (); when T thread is enabled, t thread directly obtains the execution right. Call your own run method. Specify to sleep (3000). T thread frozen for 3 seconds, this is the T thread is released

Execution right. The main thread starts to execute and print the thread test, and the main thread ends. Wait 3 seconds until the T thread prints mythread running, and then the T thread ends. The program ends.

 

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.