/*
* 启动线程的唯一方法就是通过Thread类的start()实例方法,不能直接调用run()方法。
* 从语法上来说没有错误,但是不是多线程
*
* start()方法是一个native方法,它将启动一个新线程,并执行run()方法。
*
* 这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,
* 就可以启动新线程并执行自己定义的run()方法
*
*
* public class Thread implements Runnable
*
* 重要属性
* private Runnable target;
*
* 如果不覆盖定义Thread类种的run方法,则默认调用接口方法的实现,覆盖定义时
* 不能修改方法签名
* public void run(){
* if(target!=null) target.run();
* }
*
*
* 构造器
* public Thread(Runnable target) {
this(null, target, "Thread-" + nextThreadNum(), 0);
}
public Thread(ThreadGroup group线程组, Runnable target) {
this(group, target, "Thread-" + nextThreadNum(), 0);
}
*
*
* start方法
*
* public synchronized void start() {
if (threadStatus != 0) //当前线程状态检查
throw new IllegalThreadStateException();
表示只有线程对象创建后才能调用start,如果已经调用了start再次调用会报异常
group.add(this); //将当前线程对象添加到一个线程组中进行管理
boolean started = false; //标志值用于判断当前线程是否已经启动
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}
private native void start0();//通过对等类实现启动线程的细节,内部就是自动调用run()方法
定义线程类
class LeftThread extends Thread{
//定义左手线程类,只需要覆盖(重写)定义其中的run()方法,这里实际就是线程的执行线索,执行的程序
public void run(){
for(int i=0;i<50;i++)
System.out.println("左手一个慢动作....")
}
}
调用方法
Thread t1=new LeftThread();
t1.start();//启动线程必须使用start方法,而不能是调用run方法
//t1.run();不允许直接调用run方法,因为这种调用方式不是多线程,而是单线程
最简单的方式是查看线程个数
// Thread.currentThread()用于获取当前正在运行这个代码的线程对象
System.out.println(Thread.currentThread());
Thread t1 = new LeftThread();
// t1.run();在当前主线程中执行t1对象中的run方法
// t1.start();可以在LeftThread中获取到另外一个线程对象
输出线程对象
public String toString() {
ThreadGroup group = getThreadGroup();
if (group != null) {
return "Thread[" + getName()线程名称 + "," + getPriority()优先级 + "," +
group.getName() 所属线程组的名称+ "]";
} else {
return "Thread[" + getName() + "," + getPriority() + "," +
"" + "]";
}
}
public class LeftThread extends Thread {
@Override
public void run() {// 这里包含的就是执行线索
System.out.println(Thread.currentThread());
}
}
最大的限制实际上就是Java的单根继承体系,这种方式基本不用
*
*
*/