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

发布时间:2024年01月15日

多线程


并发和并行


实现方法

代码演示

方式一

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
    }

}

文章来源:https://blog.csdn.net/qingwan_91/article/details/135605655
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。