Java多线程实现的三种方式

本文详细介绍了Java中实现多线程的三种主要方法:继承Thread类、实现Runnable接口及实现Callable接口。通过具体代码示例,展示了每种方法的使用方式,并比较了它们之间的区别。

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

Java多线程实现的三种方式
1. 第一种继承Thread 类
package com.thread;
public class Mythread extends Thread {
    private int ticket = 10;

    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            if (ticket > 0) {
                System.out.println("票数:" + this.ticket--);
            }
        }
    }
}
2.第二种实现Runnable接口(推荐)
package com.thread;
public class MyThreadImp implements Runnable {
    private int ticket = 10;

    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            if (ticket > 0) {
                System.out.println("票数:" + this.ticket--);
            }
        }
    }
}
3.第三种实现Callable接口
package com.thread;

import java.util.concurrent.Callable;

/**
 * 可以接收返回值
 * 
 * @author 李保磊
 *
 */
public class MyTreadCallable implements Callable<String> {
    private int ticket = 10;

    @Override
    public String call() throws Exception {
        for (int i = 0; i < 200; i++) {
            if (ticket > 0) {
                System.out.println("票数:" + this.ticket--);
            }
        }
        return "票已卖完";
    }
}
4.测试
package com.thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * description:实现多线程的方法与区别
 * 
 * @author 李保磊
 *
 */
public class ThreadMain {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 第一种
        // Mythread mt = new Mythread();
        // new Thread(mt).start();
        // new Thread(mt).start();
        // new Thread(mt).start();
        // 第二种
        // MyThreadImp imp = new MyThreadImp();
        // new Thread(imp).start();
        // new Thread(imp).start();
        // new Thread(imp).start();
        // 第三种
        MyTreadCallable mc1 = new MyTreadCallable();
        MyTreadCallable mc2 = new MyTreadCallable();
        FutureTask<String> task1 = new FutureTask<String>(mc1);
        FutureTask<String> task2 = new FutureTask<String>(mc2);
        new Thread(task1).start();
        new Thread(task2).start();
        System.out.println("A线程" + task1.get());
        System.out.println("B线程" + task2.get());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值