如果要想在Java之中实现多线程的定義,那麽就要有一個專門的綫程主體類进行任务的定义,
*而这个主体类的定义式亚欧要求的,必须是能实现特定的接口或者继承特定的父类才可以完成。
继承 Thread 类实现多线程
*Java里面提供有一个 Java.lang.Thread 的程序类,那么一个类只要继承此类就表示这个类为线程的主体类,
*但是并不是说Thread这个类就可以实现多线程处理 ,因为还要覆写Thread类中提供的一个 run()方法(public void run()),而这个方法
*就属于线程的主方法。
public class ThreadDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyThread("綫程A").run();
new MyThread("綫程b").run();
new MyThread("綫程c").run();
new MyThread("綫程d").run();
}
}
运行结果:
綫程1A运行, x =0
綫程1A运行, x =1
綫程1A运行, x =2
綫程2A运行, x =0
綫程2A运行, x =1
綫程2A运行, x =2
綫程3A运行, x =0
綫程3A运行, x =1
綫程3A运行, x =2
綫程4A运行, x =0
綫程4A运行, x =1
綫程4A运行, x =2
*多线程要执行的功能都应该在run()方法中进行定义。
public void run() { //线程的主体方法
// TODO Auto-generated method stub
for (int x = 0; x < 3; x++) {
System.out.println(this.title + "运行, x =" + x);
}
super.run();
}
}
通过此时的调用你可以发现,虽然调用了是start()方法 ,但是最终执行的是run()方法,并且所有的线程对象都是交替执行。
*(线程的本身执行就是交替执行的,执行顺序是不可控的)
*疑问?为什么多线程的启动不直接使用run()方法而必须使用Thread类中的start()方法呢?
以下 start源码:
public synchronized void start() {
if (threadStatus != 0) //判断线程的状态
throw new IllegalThreadStateException(); //抛出了一个异常
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}
private native void start0();//只定义方法名称
@Override
public void run() {
if (target != null) {
target.run();
}
}
在源码你会发现 start()方法里面会抛出一个“IllegalThreadStateException”异常类对象,但是
整个的程序并没有使用throws或者是明确的try…catch处理,因为该异常一定是 RuntimeException 的子类,每一个
线程类的对象只允许启动一次,如果重复启动就会抛出此异常。
观察以下代码抛出异常:
public class ThreadDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread= new MyThread("綫程A");//重复线程的启动
thread.start();
thread.start();
thread.start();
}
}
输出结果:
Exception in thread "main" 綫程A运行, x =0
java.lang.IllegalThreadStateException
綫程A运行, x =1
綫程A运行, x =2
正确使用线程代码如下:
class MyThread extends Thread { //线程的主体类
private String title;
public MyThread(String title) {
this.title = title;
}
@Override
public void run() { //线程的主体方法
// TODO Auto-generated method stub
for (int x = 0; x < 3; x++) {
System.out.println(this.title + "运行, x =" + x);
}
super.run();
}
}
public class ThreadDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyThread("綫程1A").start();
new MyThread("綫程2A").start();
new MyThread("綫程3A").start();
new MyThread("綫程4A").start();
}
}
输出结果如下:
綫程1A运行, x =0
綫程1A运行, x =1
綫程1A运行, x =2
綫程2A运行, x =0
綫程2A运行, x =1
綫程4A运行, x =0
綫程4A运行, x =1
綫程4A运行, x =2
綫程2A运行, x =2
綫程3A运行, x =0
綫程3A运行, x =1
綫程3A运行, x =2
线程的使用是交替进行系统资源抢占使用