/**
* 创建线程的三种方式,很多的是视频和课本上只讲了两种创建线程的方式,其实最骚的那种没有讲到,那就看看三种方式都是怎样创建的
*/
1.继承Thread类
public class CreateThread {
public static void main(String[] args){
//1.创建线程
MyThread thread = new MyThread(); //新建状态
thread.start(); //启动线程,就绪状态
MyThread thread1 = new MyThread(); //新建状态
thread1.start(); //启动线程,就绪状态
}
}
//线程类
class MyThread extends Thread{
@Override
public void run() {
for (int i=0;i<5; i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2.实现runnable接口
public static void main(String[] args){
//1.new 一个runnable实现类对象
MyThread1 runnable = new MyThread1();
//2.创建线程
Thread thread1 = new Thread(runnable,"thrad1"); //@param thread1是线程名称
thread1.start();
Thread thread2 = new Thread(runnable,"thrad2"); //@param thread1是线程名称
thread2.start();
}
//runnable实现类
class MyThread1 implements Runnable{
@Override
public void run() {
for (int i=0;i<5; i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3.callable和FutureTask的配置使用,这是最厉害的一个,之前的两种线程无法带返回值,callable中的call()可以带Object类型的返回值
public static void main(String[] args){
//1.new Callable接口得实现对象
MyThread3 callable = new MyThread3();
//2.创建FuturTask对象
FutureTask<Integer> ft = new FutureTask<>(callable);
//3.创建线程
Thread threa1 = new Thread(ft);
threa1.start();
try {
int sum = ft.get(); //取线程的返回值
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class MyThread3 implements Callable<Integer> {
@Override
public Integer call() {
int count = 0; //定义线程返回值
for (int i=0;i<5; i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return count;
}
}
创建线程的三种方式
最新推荐文章于 2023-06-20 09:48:03 发布