Creating and using multiple threads
First, the way to create threads
Create a common thread in two ways
1, inheritance Thread class to create a thread class.
2, to achieve Runnable interface.
Create threads - Method 1 - inheritance Thread class
can be created by a thread inheritance Thread class, the benefits of this approach is that ** this is representative of the current thread, ** do not need to get a reference to the current thread by Thread.currentThread ().
code show as below:
/**
* 描述:继承Thread类来创建线程类
*/
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // 线程开始运行
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("这里是线程运行的代码");
}
}
Create threads - Method 2 - to achieve Runnable interface
by implementing Runnable interface, and call the constructor of the Thread Runnable object as a target parameter passed to create a thread object. The advantage of this method is that you can circumvent the limitations of single class inheritance; but need to get the current thread referenced by Thread.currentThread ().
/**
* 描述:继承Thread类来创建线程类
*/
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
new Thread(t).start(); // 线程开始运行
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println("这里是线程运行的代码");
}
}
Use thread
Thread side common construction method
of the Thread class common method
ID : uniquely identifies the thread, the thread will not repeat different
name : the various debugging tools used in
the state : represents a situation in which the current thread
priority : high thread theoretically more likely to be scheduled on a background thread, We need to remember one thing: JVM will be at the end of all non-background threads of a process, before the end of the run. It is alive, that is simple to understand, to run method is running over.