Java线程创建的两种方式

本文介绍了Java中创建线程的两种主要方式:继承Thread类和实现Runnable接口。通过具体示例代码展示了这两种方法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA线程有两种创建方式:继承Thread类和实现Runnable接口

package test;

public class MyThread extends Thread {

    private String name;

    MyThread(String name) {
        this.name = name;
    }

    //线程执行方法体
    public void run() {
        System.out.println(name + " is running.");
    }

    public static void main(String[] args) {
        MyThread thread_1 = new MyThread("t1");
        MyThread thread_2 = new MyThread("t2");
        thread_1.start();//线程的执行采用start方法
        thread_2.start();
        //第二种方法
        Runnable r1 = new MyThread("r1");
        Runnable r2 = new MyThread("r2");
        Thread th1 = new Thread(r1);
        Thread th2 = new Thread(r2);
        th1.start();
        th2.start();

    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

/**
 *
 * @author hhkun
 */
public class MyRunnable implements Runnable {

    private String name;

    MyRunnable(String name) {
        this.name = name;
    }

    public void run() {
        System.out.println(name + " is running.");
    }

    public static void main(String[] args) {
        MyRunnable r1 = new MyRunnable("runnable1");
        MyRunnable r2 = new MyRunnable("runnable2");
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值