线程的存在是离不开进程的。进程如果消失线程一定会消失
注意区分线程与进程的概念
1.多线程的实现(Thread实现)
package cn.ls.xiancheng;
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name=name;
}
@Override
public void run() {
for(int x=0;x<10;x++) {
System.out.println(this.name +"-->"+x);
}
}
public static void main(String[] args) {
MyThread mt1=new MyThread("线程一");
MyThread mt2=new MyThread("线程二");
MyThread mt3=new MyThread("线程三");
mt1.start();
mt2.start();
mt3.start();
}
}
这里为什么多线程的启动时start而不是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();
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 */
}
}
}
start0();
注意这里有个start方法。这个的作用是根据操作系统的不同去进行资源的分配
所以Thread类的start方法不仅仅要启动多线程的执行代码,还要根据操作系统的不同进行资源的分配