多线程交叉

继承Thread和实现Runnable接口的区别
1.从java设计来看:通过继承Thread或者实现Runnable接口来穿件线程本质上是没有区别的,从jdk帮助文档我们可以看到Thread类本身就实现了Runnable接口。
2.实现Runnable接口方式更加适合多个线程共享一个资源的情况,并且避免了单继承的限制!

多线程实现方式

请编写一个程序,创建两个线程,一个线程输出"执行听歌",输出一百次。退出,另一个线程输出一次输出"执行游戏"一百次,退出。

继承thread

public class Mythread1 extends Thread{
    @Override
     public void run(){
         for (int i=0;i<100;i++){
             System.out.println("执行听歌"+i);
         }
     }
}
public class Mythread2 extends Thread{
    @Override
    public void start(){
        for (int j=0;j<100;j++){
            System.out.println("执行游戏"+j);
        }
    }
}
public class Threadtext1 {
    public static void main(String[] args) {
        Mythread1 t1=new Mythread1();
        Mythread2 t2=new Mythread2();
        t1.start();
        t2.start();
 
    }
}

实现Runnable

public class MyRunnable1 implements Runnable{
    @Override
    public void run() {
        for (int i=0;i<100;i++){
            System.out.println("执行听歌"+i);
        }
    }
}
public class MyRunnable2 implements Runnable {
    @Override
    public void run() {
        for (int j=0;j<100;j++){
            System.out.println("执行游戏"+j);
        }
        }
    }
public class Threadtext2 {
    /**
     * Runnable接口实现类实现多线程的步骤:
     * 1.定义类实现Rdhnable接口:
     * 2.重写run方法;
     * 3.在main方法中实例化Runnable接口的实现类对象;
     * 4.定义两个线程Thread类的对象,把Runnable接口的实现对象传入构造方法中;
     * 10 5.线程类对象调用start方法,启动线程,自动执行Runnable接口的实现类中的run方法;
     */
public static void main(String[] args) {
       MyRunnable1 r1=new MyRunnable1();
       MyRunnable2 r2=new MyRunnable2();
        //Runnable接口的实现实现多线程,必须借助Thread类才能实现
        Thread t1=new Thread(r1);
        Thread t2=new Thread(r2);

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值