多线程02

前面一节我们是通过继承Thread这个类来实现多线程,而如果当前类要继承其他类的时候,我们怎么来实现多线程呢?大家都知道,Java中只允许单从继承,也就是说不能在继承Thread这个类了,那设个时候怎么来实现多线程呢?其实,我们可以通过Runnable接口的方式实现多线程,查看API可以知道,Runnable接口中只定义了一个抽象方法:

public void run(){

}

使用Runnable接口实现多线程的格式如下。

class 类名称  implements Runnable{

属性...;

方法...;

public void run(){

线程主体;

}

}

同样,我们拿个例子来说明下:

class MyThread implements Runnable{

private String name;

public MyThread(String name){

this.name=name;

}

public void run(){

for(int i=0;i<5;i++){

System.out.println(name+"运行,i="+i);

}

}

};

public class ThreadTest{

public static void main(String args[]){

MyThread mt1=new MyThread("线程A");

MyThread mt2=new MyThread("线程B");

Thread t1=new Thread(mt1);

Thread t2=new Thread(mt2);

t1.start();

t2.start();

}

}

运行结果:

线程A运行,i=0

线程A运行,i=1

线程A运行,i=2

线程A运行,i=3

线程B运行,i=0

线程B运行,i=1

线程B运行,i=2

线程B运行,i=3

线程B运行,i=4

线程A运行,i=4

<!--EndFragment-->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值