Use threads for batch collection problems
Method 1: Inherit the Thread class
Method 2: implement the runnable interface
The most important method of the thread class is run (), which is called by the START () method of the thread class,
Thread. Join ();
I:
Public class mythread extends thread
{
Int COUNT = 1, number;
Public mythread (INT num)
{
Number = num;
System. Out. println
("Create thread" + number );
}
Public void run (){
While (true ){
System. Out. println
("Thread" + number + ": Count" + count );
If (++ COUNT = 6) return;
}
}
Public static void main (string ARGs [])
{
For (INT I = 0;
I <5; I ++) New mythread (I + 1). Start ();
}
}
Result:
Thread 1: Count 2
Create thread 3
Thread 3: Count 1
Thread 1: Count 3
Thread 1: Count 4
Thread 1: Count 5
Create thread 4
Thread 4: Count 1
Create thread 5
Thread 5: Count 1
Thread 3: Count 2
Thread 3: Count 3
Thread 4: Count 2
Thread 3: Count 4
Thread 4: Count 3
Thread 5: Count 2
Thread 5: Count 3
Thread 5: Count 4
Thread 4: Count 4
Thread 3: Count 5
Thread 4: Count 5
Thread 5: Count 5
Conclusion:Multiple Threads are executed in disorder without affecting each other.
Ii. Use Interfaces
The only difference from the above program is to generate a thread. Add a new thread (); as follows:
New thread (New mythread (I + 1). Start ();