Java thread:
A thread is the sequential control flow within a program.
The CPU actually executes only one task at a time point. However, we divide the CPU into multiple time slices. Because of the high speed, we seem to have multiple threads ..
Just like dividing your time into several slices, it seems that the efficiency will be high if you do things regularly, not to mention the cup.
Thread creation and startup:
Method 1:
Java threads are implemented through the java. Lang. Thread class.
The VM starts with a thread defined by the main method,
Each thread is a tread object that uses its run () method to complete operations.
Thread start method: Start () method of thread.
For example:
Public class testthread
{
Public static void main (string [] ARGs)
{
Runner1 r = new runner1 ();
// Define the thread object. And call the thread constructor.
Thread t = new thread (R );
// Start the thread.
T. Start ();
For (INT I = 0; I <100; I ++)
{
System. Out. println ("main thread -----" + I );
}
}
}
Class runner1 implements runnable
{
Public void run ()
{
For (INT I = 1; I <100; I ++)
{
System. Out. println ("runner1" + I );
}
}
}
Method 2:
Define a subclass of the thread class, override the run () method, and then generate the object of this class, and start the process.
Public class testthread
{
Public static void main (string [] ARGs)
{
Runner1 r = new runner1 ();
// Start the thread.
R. Start ();
For (INT I = 0; I <100; I ++)
{
System. Out. println ("main thread -----" + I );
}
}
}
Class runner1 extends thread
{
Public void run ()
{
For (INT I = 1; I <100; I ++)
{
System. Out. println ("runner1" + I );
}
}
}
Compared with the two methods, the method for implementing interfaces is more flexible.
Thread control method: