多线程实现的方式一继承Thread

时间:2023-03-08 22:00:50
多线程实现的方式一继承Thread

实现方法一:继承Thread类     

package thread;
/**
* @function 多线程继承Thread类
* @author hj
*/
public class Threads extends Thread{
private String name;
public Threads(String name) {
this.name=name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + "运行 : " + i);
try {
sleep( 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Threads mTh1=new Threads("A");
Threads mTh2=new Threads("B");
mTh1.start();
mTh2.start();
} }

运行结果如下:

B运行 : 0
A运行 : 0
A运行 : 1
B运行 : 1
B运行 : 2
A运行 : 2
B运行 : 3
A运行 : 3
B运行 : 4
A运行 : 4

多线程实现的方式一继承Thread

说明:通过上图可看出Thread类本质上是实现了rannable接口的实体类,代表一个线程的实例。启动线程的唯一的方法就是通过Thread类的start()方法。通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。

   通过结果可以看出,多行程程序是乱序执行的,因此只有乱序的情况下才有必要设计多线程。

    而sleep()方法是不让当前的线程占用该进程所有的CPU资源,留出时间给其他线程执行

如果start方法被重复调用的话,会出现以下错误(线程异常)

 public static void main(String[] args) {
Threads mTh1=new Threads("A");
Threads mTh2=mTh1;
mTh1.start();
mTh2.start();
}

  多线程实现的方式一继承Thread