I. Multithreading
1. Fake Multithreading
Example 1:
- Public ClassTestThread
- {
- IntI = 0, j = 0;
- Public VoidGo (IntFlag ){
- While(True){
- Try{
- Thread. Sleep (100 );
- }
- Catch(InterruptedExceptionE ){
- System. Out. println ("Interrupted ");
- }
- If(Flag = 0)
- I ++;
- System. Out. println ("I =" + I );
- }
- Else{
- J ++;
- System. Out. println ("j =" + j );
- }
- }
- }
- Public Static VoidMain (String[] Args ){
- NewTestThread (). go (0 );
- NewTestThread (). go (1 );
- }
- }
The running result of the above program is:
I = 1
I = 2
I = 3
...
The result will always print the I value. Our intention is that when sleep () is called in the while LOOP, another thread will start and print the value of j, but the result is not like this. The following describes why sleep () does not show the expected results.
2. Multithreading
By inheriting the class Thread or implementing the Runnable interface, we can implement multithreading.
2.1 multi-Thread implementation by inheriting class Thread
Class Thread has two most important functions: run () and start ().
1) The run () function must be overwritten. Put the code to be processed in parallel in multiple threads into this function.
2) Although the run () function implements parallel processing of multiple threads, we cannot directly call the run () function, but call the start () function to call the run () function. When you call start (), the start () function first initializes the multi-thread (this is why the run () function cannot be called directly ), then call the run () function.
Example 2:
- Public ClassTestThreadExtends Thread{
- Private Static IntThreadCount = 0;
- Private IntThreadNum = ++ threadCount;
- Private IntI = 5;
- Public VoidRun (){
- While(True){
- Try{
- Thread. Sleep (100 );
- }
- Catch(InterruptedExceptionE ){
- System. Out. println ("Interrupted ");
- }
- System. Out. println ("Thread" + threadNum + "=" + I );
- If(-- I = 0)Return;
- }
- }
- Public Static VoidMain (String[] Args ){
- For(IntI = 0; I <5; I ++)
- NewTestThread (). start ();
- }
- }
The running result is:
T