Java 中线程的使用

Java 中使用线程有两种方式:

一、继承 Thread 类
1、创建自定义类并继承 Thread 类。
2、重写 Thread 类中的 run 方法,并编写该线程的业务逻辑代码。

public class MyThread extends Thread {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        //定义业务逻辑
        for(int i = 0;i<10;i++) {
            System.out.println("-------------MyThread");
        }
    }
}

3、使用

public class Test {
     public static void main(String[] args) {
         //开启两个子线程
         MyThread thread1 = new MyThread();
         MyThread2 thread2 = new MyThread2();
         thread1.start();
         thread2.start();
     }
}

注意:不能通过 run 方法来调用线程的任务,因为 run 方法调用相当于普通对象的执行,并不会去抢占 CPU 资源。
只有通过start方法才能开启线程,进而去抢占 CPU 资源,当某个线程抢占到 CPU 资源后,会自动调用 run 方法。

二、实现 Runnable 接口
1、创建自定义类并实现 Runnable 接口。
2、实现 run 方法,编写该线程的业务逻辑代码。

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<1000;i++) {
            System.out.println("========MyRunnable=======");
        }
    }
}

3、使用。

MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
MyRunnable2 runnable2 = new MyRunnable2();
Thread thread2 = new Thread(runnable2);
thread2.start();

三、两种方式的区别:
1、MyThread,直接在类中重写 run 方法,使用的时候直接实例化 MyThread,使用start()方法开启线程 即可,因为 Thread 内部存在 Runnable。

2、MyRunnbale,在实现类中重写 run 方法,使用的时候需要先创建 Thread 对象,并将 MyRunnable 注入到 Thread 中,之后使用start()方法开启线程。

实际开发中推荐使用第二种方式,可以降低代码耦合度。

四、线程和任务:
线程是去抢占 CPU 资源的,任务是具体执行业务逻辑的,线程内部会包含一个任务,线程启动(start),当抢占到资源之后,任务就开始执行(run)。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值