A, create a thread
Create a Thread ways mainly have two kinds, say two, we point into the source code to see, is actually a kind of way, because the Thread class is to implement the Runnable interface, in its form,
The first: through inheritance Thread class rewrite the run method:
Public class CreateThread {
Public static void main (String [] args) {
Thread the t1=new MyThread ();
//start the thread
T1. Start ();
}
}
The class MyThread extends Thread {
@ Override
Public void the run () {
System. Out.println (" create a thread!" );
}
}
Shorthand:
//an anonymous inner class
New Thread () {
@ Override
Public void the run () {
System. Out.println (" create a thread!" );
}
}. The start ();
1
Second: by implementing the Runnable interface to rewrite the run method:
Public class createThread {
Public static void main (String [] args) {
//instantiate the task
A Runnable r1=new MyRunnable ();
//create a thread specified tasks at the same time
Thread the t1=new Thread (r1);
//equal Thread t1=new Thread (new MyRunnable)
T1. Start ();
}
}
The class MyRunnable implements Runnable {
@ Override
Public void the run () {
System. Out.println (" create a thread!" );
}
}
Shorthand:
New Thread (new Runnable () {
@ Override
Public void the run () {
System. Out.println (" create a thread!" );
}
}).start();
1
The simplest way to Lambda expressions:
New Thread (() - & gt; System. Out.println (" create a thread!" )). The start ();