实现java多线程的第二种办法:实现runable接口

1、为什么用runable接口

对于java来说不能实现多继承,所以说,对于一个类来说,如果有自己的父类,但是还要想继承线程(thread类)类的话,就出现问题啦。


2、实现runable接口,此接口就有一个方法,run()。此run()方法用于执行线程任务。

class Demohehe implements Runnable //但是Demohehe不是线程对象

所以,还要创建线程对象.

在thread的构造函数中,有一个是带有runable接口的构造函数。

Thread(Runnable target)
          分配新的 Thread 对象。

Demohehe t1 = new Demohehe(); 

Thread nt1 = new Thread(t1);

Thread nt2 = new Thread(t1);

nt1.start();
nt2.start();

3、代码

package com.xiancheng;


class Demohehe implements Runnable
{
 
   public void run()
   {
  for(int x=0;x<=10;x++)
  {
  for(int y=0;y<=99999999;y++){}
   System.out.println(Thread.currentThread().getName()+"....x="+x);
  }
   }
}




public class hello {
public static void main(String[] args){

Demohehe t1 = new Demohehe(); 
Thread nt1 = new Thread(t1);
Thread nt2 = new Thread(t1);
nt1.start();
nt2.start();
}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值