Java多线程——并发和并行、实现方法

本文详细讲解了Java中通过继承Thread、实现Runnable接口和FutureTask进行多线程的方式,并通过实例展示它们的运作过程。

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

多线程


并发和并行


实现方法

代码演示

方式一

package com.qiong.thread1;

public class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(getName() + "Hello World");
        }
    }
}
package com.qiong.thread1;

public class ThreadDemo1 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

        t1.setName("线程一");
        t2.setName("线程二");

        //开启线程
        t1.start();
        t2.start();

        /*
        线程二Hello World
        线程二Hello World
        线程二Hello World
        线程一Hello World
        线程一Hello World
        线程二Hello World
        线程一Hello World
         */
    }
}

方式二

package com.qiong.thread2;

public class MyRun implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            Thread thread = Thread.currentThread();

            System.out.println(thread.getName() + "Hello World");
        }
    }
}
package com.qiong.thread2;

public class ThreadDemo {
    public static void main(String[] args) {
        MyRun mr = new MyRun();

        Thread t1 = new Thread(mr);
        Thread t2 = new Thread(mr);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();

        /*
        线程二Hello World
        线程二Hello World
        线程二Hello World
        线程一Hello World
        线程一Hello World
        线程二Hello World
        线程一Hello World
         */
    }
}

方式三

package com.qiong.thread3;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        //求1~100之间的和
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        return sum;
    }
}
package com.qiong.thread3;

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

public class ThreadDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable mc = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<>(mc);
        Thread t1 = new Thread(ft);
        t1.start();

        Integer result = ft.get();
        System.out.println(result);//结果:5050
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值