当前位置: 移动技术网 > IT编程>开发语言>Java > Java多线程继承Thread类详解第1/2页

Java多线程继承Thread类详解第1/2页

2019年07月22日  | 移动技术网IT编程  | 我要评论
调用方法: /** * 点击量/月(年)thread */ public void yearlyclickthread() { // 获取参数

同样给大家分享下网友的实例

package javathread;class firstthread extends thread{ private string name = null; public firstthread(string str) {  this.name = str; } public void run() {  for(int i=1;i<=3;i++)  {   system.out.println("线程"+this.name+"第"+i +"执行");   try {    thread.sleep(50);   } catch (interruptedexception e) {        e.printstacktrace();   }  } }}class secondthread extends thread{ private string name = null; public secondthread(string s) {  this.name = s; } public void run() {  for(int i=1;i<=3;i++)  {   system.out.println("线程"+this.name+"第"+i +"执行");   try {    thread.sleep(50);    thread.yield();   } catch (interruptedexception e) {     e.printstacktrace();   }  } }}public class testthread{ public static void main(string[] args) {  firstthread p = new firstthread("first");  secondthread pth = new secondthread("second");  p.setpriority(4);  pth.setpriority(9);  p.start();  pth.start(); }}

简单讲下继承thread类

                步骤:
                a,定义类继承thread类。
                b,覆盖thread类中的run方法,将需要被多线程执行的代码定义到该run方法当中。
                c,建立thread类的子类创建线程对象。
                d,调用start方法,开启线程并调用该线程的run方法。

        下面有个示例来让你直观的了解怎么用继承thread类的方式来创建线程。

  /*  * 示例:创建三个线程,每过2秒打印一下线程的名称,打印三次  */  public class thread1 extends thread{    private final int max = 3;//最大打印次数    private int count = 1;//计数    private final int time = 2;//间隔时间      //接收线程名称    public thread1(string name) {      super(name);    }    //覆盖run方法,在里面写我们要执行的代码    public void run() {      while(count<= max){        system.out.println(this.getname());        count++;        //每次打印后,在一段时间后再打印        try {          thread.sleep(time*1000);        } catch (interruptedexception e) {          e.printstacktrace();        }      }    }    public static void main(string[] args) {      thread1 t1 = new thread1("线程1");//创建线程      thread1 t2 = new thread1("线程2");      thread1 t3 = new thread1("线程3");      t1.start(); //开启线程      t2.start();      t3.start();      //也可以使用下面这种方式书写      //new thread1("线程4").start();    }  }

2

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网