线程创建的四个方式

Thread:继承Thread类实现多线程

run()为线程类的核心方法,相当于主线程的main方法,是每个线程的入口

a.一个线程调用 两次start()方法将会抛出线程状态异常,也就是的start()只可以被调用一次

b.native生明的方法只有方法名,没有方法体。是本地方法,不是抽象方法,而是调用c语言方法 registerNative()方法包含了所有与线程相关的操作系统方法

c. run()方法是由jvm创建完本地操作系统级线程后回调的方法,不可以手动调用(否则就是普通方法)

public class MyThread extends Thread {
public MyThread() {}
public void run() {
for(int i=0;i<10;i++) {
System.out.println(Thread.currentThread()+":"+i);
	}
}
public static void main(String[] args) {
MyThread mThread1=new MyThread();
MyThread mThread2=new MyThread();
MyThread myThread3=new MyThread();
mThread1.start();
mThread2.start();
myThread3.start();
	}
}
public class Test extents Thread {
public void run() {
// 重写Thread的run方法
System.out.println("dream");
	}
public static void main(String[] args) {
new Test().start();
	}
}

Runnable

java中,如果子类已经继承(extends)了一个类,就无法再直接继承Thread类,因此通过实现runnable接口来创建进程。
2.覆写Runnable()接口实现多线程,而后同样覆写run().推荐此方式

a.覆写Runnable接口实现多线程可以避免单继承局限
b.当子类实现Runnable接口,此时子类和Thread的代理模式(子类负责真是业务的操作,thread负责资源调度与线程创建辅助真实业务。(解耦合)

public class Test {
public static void main(String[] args) {
new Thread(() -> {
System.out.println("dream");
}).start();
}
}

继承Thread和实现Runnable接口的区别

a.实现Runnable接口避免多继承局限
b.实现Runnable()可以更好的体现共享的概念

Callable

覆写Callable接口实现多线程(JDK1.5)

a.核心方法叫call()方法,有返回值
b.有返回值

 public class Test {
 public static void main(String[] args) {
 // FutureTask 构造方法包装了Callable和Runnable。
 FutureTask<Integer> task = new FutureTask<>(() -> {System.out.println("dream");
 return 0;
 });
 new Thread(task).start();
 }
 }

线程池

通过Executor 的工具类可以创建三种类型的普通线程池:

public class Test {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(1);
threadPool.submit(() -> {System.out.println("dream");
});
threadPool.shutdown();
}
}

javaRunnable和Callable有啥区别?

@FunctionalInterfacepublic interface Runnable {
/** * 被线程执行,没有返回值也无法抛出异常 */
public abstract void run();
}

@FunctionalInterfacepublic interface Callable<V> {
/** * 计算结果,或在无法这样做时抛出异常。 * 
@return 计算得出的结果 * 
@throws 如果无法计算结果,则抛出异常 */
V call() throws Exception;
}
1. Runnable没有返回值并且无法抛出异常
2. Callable可以做到你不能做到的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值