java基础三线程

JAVA 线程初探

java创建线程方式只有new Thread,底层是native方法涉及到C++

运行方式有三种分别为  

1、继承Thread类

2、实现Runnable接口的实现类,重写run方法(无返回值)

3、实现Callable接口的实现类,重写run方法(有返回值)(一般用在线程池中)

由于java是单继承,所以第一种放不建议使用,

下面看下三种方式的代码:

1、继承Thread类

package com.Demo01;
public class Thread_test { public static void main(String[] args) { // 3、实例化你的类 MyThread myThread = new MyThread(); // 4、运行start方法,启动线程,观察运行结果,注意,如果这里是run的话,就会相当于普通的方法调用,不会开启一个新的线程 myThread.start(); // 5、其实可以使用lambda表达式来简写这个案例 // new Thread(()->{for (int i = 0; i < 10; i++) {System.out.println("线程执行:"+i);}}).start(); for (int j = 0; j< 10; j++) { System.out.println("主线程执行:"+j); } } } //1、创建自己的线程类继承Thread class MyThread extends Thread{ // 2、重写run方法,把需要执行的任务封装到run方法里面 @Override public void run(){ for (int i = 0; i < 10; i++) { System.out.println("线程执行:"+i); } } }

2、实现Runnable接口

package com.Demo01;

public class Runnable_test {


    public static void main(String[] args) {
//    3、创建线程对象
//      3.1 创建Runnable接口的实现类
        MyRunnable myrun = new MyRunnable();
//      3.2 利用Thread接口,创建线程
        Thread thread = new Thread(myrun);
//      3.3 运行线程
        thread.start();

        for (int j = 0;  j< 10; j++) {
            System.out.println("主线程执行:"+j);
        }
    }
}

//  1、定义Rrunnable接口的实现类
class MyRunnable implements Runnable{
//  2、重写run方法
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Runnable线程执行:"+i);
        }
    }
}

3、callable实现

package com.Demo01;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Callable_test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//      3、创建Callable接口的实现类对象
        MyCallable myCallable = new MyCallable();
//      4、借助FutureTask实现类RunableFuture接口,该接口继承了Runable接口
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
//      5、再传递给Thread
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println("主线程可以获取子线程的结果");
        System.out.println("result=:"+futureTask.get());
    }
}

//callable接口中的call()有返回值,通过callable泛型,返回指定的类型
//  1、创建callable的实现类
class MyCallable implements Callable{
//  2.重写call方法,编写返回类型
    @Override
    public Integer call() throws Exception {
        int result = new Random().nextInt(100);
        System.out.println("线程完成计算,结果为"+result);
        return result;
    }
}

一般callable方法用在线程池中

原文地址:https://www.cnblogs.com/Robertzewen/p/11178963.html