java线程学习之线程创建

时间:2023-03-09 01:07:20
java线程学习之线程创建

线程是程序控制的一个内部数据流。线程的状态转化如下

java线程学习之线程创建

或者

java线程学习之线程创建

在java中创建线程有两种方式:

1.实现runnable接口(这个比较好,推荐这个。原因是:用的时候比较灵活,相比较继承Thread类,用接口来实现可以减少资源使用,比较继承也是一种宝贵资源,毕竟Java是单继承多实现)

2.继承Thread类(Thread类实现了Runnable方法)

利用Runnable接口启动线程的方法是:先创建Runnable接口的实现类,然后将实现类的实例作为参数传给Thread的构造方法,最后调用start方法。

利用继承Thread类来启动线程的方法是:先创建Thread类的子类,然后创建子类的实例,最后调用start方法。

两种方式均是利用Thread类的Start方法。

 /**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
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();
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 */
}
}
}

jdk中Thread类的start方法

例子一:实现runnable接口

 package com.song.test;

 public class TestRunnable implements Runnable {
public void run() {
System.out.println("线程启动....");
}
public static void main(String[] args) {
System.out.println("测试线程一....");
TestRunnable test=new TestRunnable(); //创建实现类的实例
Thread t1=new Thread(test); //将实现类的实例作为参数传给Thread的构造方法
t1.start();//调用start方法启动线程
}
}

运行结果:

java线程学习之线程创建

java的jdk1.6对java.lang.Runnable的解释

java线程学习之线程创建

2例子二:继承Thread类

 package com.song.test;

 public class TestThread01 extends Thread {
public static void main(String[] args) {
System.out.println("开始执行");
TestThread01 test = new TestThread01();
test.start();
} @Override
public void run() {
System.out.println("用继承Thread的线程已启动");
}
}

结果为:

java线程学习之线程创建

使用的jdk1.6的解释为:

java线程学习之线程创建

关于线程终止:是指除守护线程以外的线程全部终止,守护线程是执行后台作业的线程。当进入main方法中执行程序时就已经启动了主线程,在主线程执行过程中创建了另一个线程 A,且利用start()方法启动它,这时是启动两个线程,main线程和A线程。当main方法代码执行完毕,即主线程才为终止。但如果此时线程A仍在执行中,即A线程仍在运行状态不能说此时程序终止,也就是说所以程序均终止后,程序才能终止。

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

能力有限,不喜勿喷,欢迎指错。