线程的创建
线程的分类
- 用户线程:执行完后才可以停下,用户创建的线程默认为用户线程
- 守护线程:保护用户线程,Java虚拟机不会因为守护线程是否执行完毕而等待
线程的三种创建形式:
- 继承Thread类
- 实现Runnnable接口
- 实现Callable接口
注: 在面向对象中尽量多用实现少用继承,因为在Java中存在单继承的局限性。
Thread类
public class Thread
extends Object
implements Runnable
不难发现,Thread的底层实际也是实现了Runnable接口,所以必须重写run()方法,否则该线程就会是一个空线程,就会没有线程体。
使用方法:
/**
* @Description线程的创建
* @version 1.0
* @since JDK1.8
* @author Li-Ying
* @date 2020年4月18日 上午8:51:20
*/
public class Creation {
public static void main(String [] args) {
PrimeThread primeThread=new PrimeThread(10);
//启动线程调用start(),而不是调用run()
primeThread.start();
}
}
class PrimeThread extends Thread{
long minPrime;
PrimeThread(long minPrime)
{
this.minPrime=minPrime;
}
public void run()
{
System.out.println("Thread线程创建成功");
}
}
start()
start():导致线程开始执行,Java虚拟机开始调用此线程的run()方法
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);//将其加到组里面
boolean started = false;
try {
start0();//调用strat0()方法
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native void start0();//是一个本地方法,直接和CPU打交道
/**
* @Description:start()方法
* @version 1.0
* @since JDK1.8
* @author Li-Ying
* @date 2020年4月18日 上午10:28:46
*/
public class Creation_01 extends Thread{
/*
*此处作为线程的入口点
*/
@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
for(int i=0;i<20;i++)
{
System.out.println("写作业");
}
}
public static void main(String [] args) {
Creation_01 thCreation_01=new Creation_01();
//启动线程,由Java虚拟机决定什么时候调用run()方法
thCreation_01.start();
//直接调用run()方法,就变成了普通的方法体
//thCreation_01.run();
for(int i=0;i<20;i++)
{
System.out.println("听歌");
}
}
}
### Runnable
由于Runnable接口中没有start()方法,不具备和CPU直接交互的能力,所以在使用Runnable创建线程,最后在启动线程的时候需要借助Thread对象。
//Thread对象为代理对象,PrimeRun为目标对象
PrimeRun primeRun=new PrimeRun(10);
new Thread(primeRun).start();