Java Threads:
A thread is a sequential flow of control within a program.
The CPU actually executes one at a point in time. It's just that we split the cup into multiple time slices, and because it's very fast, we look like multiple threads.
Just like your time is divided into several pieces, so the overall seems to do things regularly, efficiency will be high, not to mention is the cup.
To create and start a thread:
Method One:
Java threads are implemented by Java.lang.Thread classes.
The VM starts with a thread defined by the main method,
Each thread is the tread object through its run () method to complete the operation.
Start thread mode: the start () method of thread.
For example:
public class Testthread
{
public static void Main (string[] args)
{
Runner1 r = new Runner1 ();
Defines the thread object. and calls the thread's construction method.
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 Two:
Define a subclass of the thread class, override the Run () method, and then generate the object for this class in the START 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);
}
}
}
The method of implementing interface is more flexible than two methods.
Thread Control methods: