您的位置:首页 > 编程语言 > Java开发

Java知识梳理——线程实现/创建方式

2019-09-02 16:10 46 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_38905818/article/details/100293519

方法1:Thead

Thread 类本质上是实现了 Runnable 接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过 Thread 类的 start()实例方法。start()方法是一个 native 方法,它将启动一个新线程,并执行 run()方法。

[code]public class Main extends Thread{
public static void main(String[] args) {
Main myThead=new Main();
myThead.start();
}
public void run(){
System.out.println("start thread");
}
}

方法2:Runnable

如果自己的类已经 extends 另一个类,就无法直接 extends Thread,此时,可以实现一个Runnable 接口。

[code]public class Main implements Runnable{
public static void main(String[] args) {
Main myThead=new Main();
Thread thread=new Thread(myThead);
thread.start();
}
public void run(){
System.out.println("start thread");
}
}

方法3:Callable

有返回值的任务必须实现 Callable 接口,类似的,无返回值的任务必须 Runnable 接口。执行Callable 任务后,可以获取一个 Future 的对象,在该对象上调用 get 就可以获取到 Callable 任务 返回的 Object 了。

Callable所依赖的FutureTask类保存了call方法的返回值,可以用get方法获取。

[code]import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Main implements Callable<Integer> {
public static void main(String[] args) throws Exception {
Main myThead=new Main();
FutureTask futureTask=new FutureTask(myThead);
Thread thread=new Thread(futureTask);
thread.start();
System.out.println(futureTask.get());
}
public Integer call(){
return 1;
}
}

方法4:线程池

线程和数据库连接这些资源都是非常宝贵的资源。那么每次需要的时候创建,不需要的时候销 毁,是非常浪费资源的。那么我们就可以使用缓存的策略,也就是使用线程池。

基本的线程池有:(1)newFixedThreadPool(2)newSingleThreadExecutor(3)newCachedThreadPool (4)newScheduledThreadPool

[code]import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
public static void main(String[] args) throws Exception {
ExecutorService pool=Executors.newFixedThreadPool(10);

for(int i=0;i<5;i++)
{
Runnable r=new Runnable() {
@Override
public void run() {
Thread thread=new Thread();
System.out.println(thread.getName());
}
};
pool.execute(r);
}
pool.shutdown();
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: