java中线程创建

本文介绍了Java中创建线程的两种方式:一是通过继承Thread类并调用start方法,二是实现Runnable接口并用Thread对象启动。在两种方法中,start方法启动线程并调用run。使用Runnable可实现资源共享,适合多个线程共享同一资源的情况。
摘要由CSDN通过智能技术生成

        本文介绍java中两种线程创建的方法,第一种是通过继承Thread类然后调用其start方法,第二种是实现Runnable接口然后代理调用。

      下面是第一种创建方法

package ThreadExercise;

/**
 *  version 2.0
 */
public class therad {
    public static void main(String[] args) {
        Cat cat  = new Cat();
        cat.start();
   //在底层JVM调用start0方法,start0会调用run方法,所以start才是线程的开始,并不是run
        try {
            for (int i = 0; i < 4; i++) {
                System.out.println(i);
                Thread.sleep(1000);//会抛出异常所以进行了异常捕获
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class Cat extends Thread{
    int time = 0;
    public void run(){
        try {
            while (true){
                Thread.sleep(1000);
                System.out.println(++time+Thread.currentThread().getName());//获取当前线程 
  的名字
                if(time == 60 ){
                    break;
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);//会抛出异常所以进行了异常捕获
        }
    }
}

  当我们的程序开始运行时会成为一个进程,执行到main方法是会创建一个名为main的线程,执行到start时又会创建一个子线程。需要注意的是当主线程结束时,子线程不会立即结束,而是会继续执行,直到结束。

   这是第二种创建方法

package ThreadExercise;

/**
 * @author庞慧斌最牛逼~~ version 2.0
 */
public class runable {
    public static void main(String[] args) {
        Dod dod = new Dod();//实现了Runnable接口的对象实例
        Thread thread = new Thread(dod);//将dod对象作为参数传入Thread类
        thread.start();
    }
}

class Dod implements Runnable{
    @Override
    public void run() {
        int i = 0;
        while (true){
            System.out.println(++i+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (i==5){
                break;
            }
        }
    }
}
//这部分是模拟Thread类,以便于理解通过接口创建线程

class ThreadCopy{
    private Runnable thread = null;

    public ThreadCopy(Runnable thread) {
        this.thread = thread;
    }
    public void Start(){
        Start0();
    }
    public void Start0(){
        run();
    }
    public void run(){
        if(thread!=null){
            thread.run();
        }
    }
}

以上就是两种创建方式,个人感觉使用上没有什么本质的区别,唯一的就是用Rannable的话可以将同一个对象作为参数传入不同的线程,做到资源共享。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值