Notes for multithreading:
1. This. Wait () and this. Sort y () must be used in pairs;
2. Be careful with sychronized. Be careful when locking or not locking. If you use sychronized, the efficiency may decrease and unexpected results may not be caused.
3. There is a big difference between wait and thread. Sleep:Wait is the method in the object class, and sleep is the method under the thread. Wait indicates that the current thread performs wait...
Sleep controls the waiting time before execution.
4. There are two ways to create a thread:
1: Class mythread implements runnable {
Public void run (){
......
}
}
Mythread Mt = newMythread();
Thread t = new thread (MT );
T. Start ();
2. inherit from thread
Class mythread extends thread {
Public void run (){
......
}
}
}
Mythread Mt = newMythread();
Mt. Start ();
The following uses a steamed nest as an example:Consumer producerCode:
Public Class Producerconsumer { Public Static Void Main (string ARGs []) {synstack Ss = New Synstack (); producer P =New Producer (SS); consumer c = New Consumer (SS); thread t = New Thread (p); thread t2 = New Thread (c); T. Start (); t2.start ();}} Class Wotou { Int ID; wotou ( Int _ Id) {id = _ id ;} Public String tostring (){ Return ID ;}} Class Synstack {wotou [] arrwotou = New Wotou [6]; // The steamer size is 6
Private IntIdx = 0;Public Synchronized VoidPush (wotou wt ){// If (idx = arrwotou. Length ){// If an if interrupt error occurs, the object jumps out of the IF body.
While(Idx = arrwotou. Length ){Try{System. Out. println ("To handle wotou .. please wait '''");This. Wait ();//
}Catch(Interruptedexception e) {e. printstacktrace () ;}} arrwotou [idx ++] = wt;This. Notify ();// Notify the specified object ..Which of the following information is waiting for the current process to wake them up.
}Public SynchronizedWotou POP (){// If (idx = 0 ){While(Idx = arrwotou. Length ){Try{System. Out. println ("No wotou .. please wait '''");This. Wait ();//It refers to the current thread for wait...
}Catch (Interruptedexception e) {e. printstacktrace ();}} This . Notify (); Return Arrwotou [-- idx];} Class Producer Implements Runnable {synstack Ss = Null ; Producer (synstack _ SS) {Ss = _ ss ;} Public Void Run (){ For ( Int I = 0; I <20; I ++) {wotou Wt = New Wotou (I); system. Out. println ("Produce: "+ Wt); SS. Push (wt ); Try {Thread. Sleep (3000 );} Catch (Interruptedexception e) {e. printstacktrace ();}}}} Class Consumer Implements Runnable {synstack Ss = Null ; Consumer (synstack _ SS) {Ss = _ ss ;} Public Void Run (){ For ( Int I = 0; I <20; I ++) {wotou Wt = New Wotou (I); system. Out. println (" Consume: "+ Wt); SS. Pop (); system. Out. println (wt ); Try {Thread. Sleep (1000 );} Catch (Interruptedexception e) {e. printstacktrace ();}}}}
You can change the wait, policy, and so on in the Code. Let's take a look at its function ..