第一种:继承Thread类,重写它的Run方法。
实例:
public class Test_thread extends Thread{
@Override
public void run() {
//重写编写父类
System.out.println("我是Thread 方式");
//输出一个循环
for (int i = 0; i < 2; i++) {
System.out.print(i+ " ");
}
}
public static void main(String[] args) {
Test_thread t = new Test_thread();
Thread t2 = new Thread(t);
t2.start();
}
}
截图如下:

第二种:实现Runnable 接口,重写run方法
实例:
public class Test_Runnable implements Runnable{
@Override
public void run() {
//实现父类的方法
System.out.println("我是Runnable 方式实现多线程");
}
public static void main(String[] args) {
Test_Runnable t =new Test_Runnable();
new Thread(t).start();
}
}
截图如下:

第三种:实现callable接口,重写这个call()方法
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Test_callable implements Callable<Object>{
@Override
public Object call() throws Exception {
return "我是callable";
}
public static void main(String[] args) throws Exception{
Test_callable t =new Test_callable();
FutureTask<Object> task = new FutureTask<>(t);
new Thread(task).start();
System.out.println(task.get());
}
}
截图如下:

第四种:采用这个线程池的方式,ExecutorService对象
实例:
public class Test_threadPool {
/**
* 利用线程池:
* 先要实现这个Runnable 接口
* 后在实例化这个ExecutorService。
* @param args
*/
public static void main(String[] args) {
// 下面的这条语句是在线程池中定义5个线程容量
ExecutorService executorService =Executors.newFixedThreadPool(5);
// 下面的意思为,executorservice执行一个new A()对象,
executorService.execute(new A());
//下面的表示终结所有的线程对象
executorService.shutdown();
}
}
class A implements Runnable{
@Override
public void run() {
System.out.println(" A ");
}
}
截图如下:

本篇只是介绍实现多线程的方式,它们之间的联系请看后面内容。。。。。。

492





