Java中的多线程

Java中的多线程

  • 创建线程的方式:1.继承Thread类,重写run()方法,调用start开启线程
    举个例子:
package thread;

public class TestThread01 extends Thread{
    @Override
    public void run() {
        for(int i=1;i<20;i++){
            System.out.println("haha"+i);
        }
    }

    public static void main(String[] args) {
        TestThread01 testThread01=new TestThread01();
        testThread01.start();
        for (int i=1;i<5;i++){
            System.out.println("hehe"+i);
        }
    }
}

如上所示,在重写的run()方法中有for循环,而在main()方法中也有for循环,因为线程是交替执行的,所以结果应该是交替出现的
输出结果
2.实现Runnable接口:定义MyRunnable类实现Runnable接口,实现run()方法,编写线程执行体,创建线程对象,调用start()方法启动线程

package thread;

public class TestThread02 implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i < 20; i++) {
            System.out.println("haha" + i);
        }
    }

    public static void main(String[] args) {
        TestThread02 testThread02=new TestThread02();
        Thread thread=new Thread(testThread02);
        thread.start();
        for (int i = 1; i < 5; i++) {
            System.out.println("hehe" + i);
        }
    }
}

程序跟上边的差不多,唯一的区别是:在main()方法中,先创建了当前类的对象,又创建了Thread的对象,最终将当前类的对象注入到Thread对象内,并用Thread对象start线程

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值