多线程 - 1.多进程和多线程的简单实现

创建多线程——继承 Thread
public class test0 {
    public static void main(String[] args) {
        Thread MyThread = new MyThread();
        MyThread.start();
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("hello myThread" + Thread.currentThread().getName());
    }
}
创建多线程——实现 Runnable
public class test1 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

class MyRunnable implements Runnable{
    @Override
    public void run(){
        System.out.println("hello myRunnable" + Thread.currentThread().getName());
    }
}
实现多线程传参——有参构造
class ThreadA extends Thread{
    private String age;
    public ThreadA(String age){
        this.age = age;
    }
    @Override
    public void run() {
        System.out.println("age=" + age);
    }
}

public class test2 {
    public static void main(String[] args) {
        String age = new String("12");
        ThreadA a = new ThreadA(age);
        a.start();
    }
}
实现多线程返回值——实现 Callable
import java.util.concurrent.Callable;

public class test3 {
    public static void main(String[] args) {
        MyCallable MyCallable = new MyCallable("xxx");
        String call = null;
        try {
            call = MyCallable.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(call);
    }
}

class MyCallable implements Callable<String>{
    private String name;
    public MyCallable(String name) {
        this.name = name;
    }
    @Override
    public String call() throws Exception {
        return "call:" + name;
    }
}
  1. java 不允许多继承,如果继承了 Thread 类就不能再继承其他类了
  2. 实现 Runnable 的类只是做好了一段多线程所需执行的内容,自身并没有执行的能力
  3. 需要实例化一个Thread 类做启动,Thread 类也实现了 Runnable 接口
  4. run() 方法不具备传参能力,传参需要使用线程初始化的有参构造
  5. 实现 Callable< V > 的接口,可以直接使用 .call() 进行启动,且call()函数有返回值

猜你喜欢

转载自blog.csdn.net/weixin_43845524/article/details/106794863