Java 多线程实现

如果要想在Java中实现多线程的三种途径:

  • 继承Thread类;
  • 实现Runnable接口;
  • 实现Callable接口;

继承Thread类

需要覆写Thread类中的run方法。

package thread;
//线程操作主类
class MyThread extends Thread//这是一个多线程的操作类
{
	private String name ;
	public MyThread(String name)
	{
		this.name = name;
	}
	@Override
	public void run() {//覆写run()方法,作为线程的主体操作方法
		for(int x = 1 ; x < 51 ; x++)
		{
			System.out.println(this.name + "-->"+x);
		}
	}
}
public class ThreadTest 
{
	public static void main(String[] args) 
	{
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程B");
		MyThread mt3 = new MyThread("线程C");
		
		mt1.start();
		mt2.start();
		mt3.start();
	}
}

实现Runnable接口

需要实现run()方法。

package thread;
class MyThread implements Runnable//这是一个多线程的操作类
{
	private String name ;
	public MyThread(String name)
	{
		this.name = name;
	}
	@Override
	public void run() {//覆写run()方法,作为线程的主体操作方法
		for(int x = 1 ; x < 51 ; x++)
		{
			System.out.println(this.name + "-->"+x);
		}
	}
}
public class ThreadTest 
{
	public static void main(String[] args) 
	{
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程B");
		MyThread mt3 = new MyThread("线程C");
		
		new Thread(mt1).start();
		new Thread(mt2).start();
		new Thread(mt3).start();
	}
}

实现Callable接口

package com.zjw;

import java.util.concurrent.*;

public class Test03 {
    public static void main(String[] args) {
       MyCallable callable = new MyCallable();
        FutureTask<Integer> future = new FutureTask<>(callable);
        new Thread(future).start();

        try {
            Thread.sleep(1000);
            System.out.println("hello begin");
            System.out.println(future.isDone());
            //接收返回结果
            System.out.println(future.get());
            Integer result = future.get();
            System.out.println(result);

            System.out.println(future.isDone());
            System.out.println("hello end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class MyCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        for (int i = 0;i<10;i++){
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
        return 123;
    }
}

FutureTask继承关系图

参考:
Java-多线程:Callable接口和Runnable接口之间的区别
Java Runnable与Callable区别
Java并发编程:Callable、Future和FutureTask

posted @ 2020-09-10 10:56  雨中遐想  阅读(122)  评论(0编辑  收藏  举报