方法1:Thead
Thread 类本质上是实现了 Runnable 接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过 Thread 类的 start()实例方法。start()方法是一个 native 方法,它将启动一个新线程,并执行 run()方法。
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 接口。
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方法获取。
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
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();
}
}