一,概括
二,线程构建方式一(继承Thread类)
三,案例
父类:
package Duoxiancheng;public abstract class Name {public static void main(String[] args) {//3,创建一个Thread线程类对象Thread t1 =new ZHiLeiA();//4,启动线程t1.start();for (int i = 0; i < 4; i++) {System.out.println("软件");}}}
子类:
package Duoxiancheng;
/*
1.让子类继承Thread线程类
* */public class ZHiLeiA extends Thread {//2,必须重写父类的run方法;@Overridepublic void run(){for (int i = 0; i <4 ; i++) {System.out.println("星火666");}}
}
注意事项:
四,线程构建方式二(实现Runnable接口)
五,案例
父类:
package Duoxiancheng;public class Name2 {public static void main(String[] args) {//3,创建任务对象Runnable r =new ZhiLieB();//4,把任务对象处理new Thread(r).start();for (int i = 0; i < 5; i++) {System.out.println("主线程运行"+i);}}
}
子类:
package Duoxiancheng;
//1,实现Runnable接口
public class ZhiLieB implements Runnable {//2,重写run方法@Overridepublic void run() {//执行任务for (int i = 0; i < 5; i++) {System.out.println("次线程运行"+i);}}
}
注意事项:
六,线程创建方式二的匿名内部类(简化写法)
七,案例:
package Duoxiancheng;public class Name2_2 {public static void main(String[] args) {//1,直接创建Runnable接口的匿名内部类
// Runnable r =new ZhiLieB(){
// @Override
// public void run() {
// //执行任务
// for (int i = 0; i < 5; i++) {
// System.out.println("次线程运行"+i);
// }
// }
// };
// new Thread(r).start();
// for (int i = 0; i <5 ; i++) {
// System.out.println("主线程运行"+i);
// }
// }//2,简化一
// new Thread(new Runnable() {
// @Override
// public void run() {
// for (int i = 0; i < 5; i++) {
// System.out.println("次线程运行"+i);
// }
// }
// }).start();
// for (int i = 0; i <5 ; i++) {
// System.out.println("主线程运行"+i);
// }//3,简化二new Thread(()->{for (int i = 0; i < 5; i++) {System.out.println("次线程运行"+i);}}).start();for (int i = 0; i <5 ; i++) {System.out.println("主线程运行"+i);}}
}
八,线程构建方式三(实现Gallable接口)
九,案例
父类:
package Duoxiancheng;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;public class Name3 {public static void main(String[] args) throws ExecutionException, InterruptedException {//3,创建一个callable的对象Callable<String> call =new ZhiLieC(100);//4,封装对象FutureTask <String>f1=new FutureTask<>(call);//5,交给线程对象new Thread(f1).start();//6,获取线程执行后的结果String rs =f1.get();System.out.println(rs);}
}
子类:
package Duoxiancheng;import java.util.concurrent.Callable;
//1,实现接口
public class ZhiLieC implements Callable<String> {private int n;public ZhiLieC(int n){this.n=n;}//2,重写call方法@Overridepublic String call() throws Exception {//描述线程任务,返回结果//例:求1-n的和返回int sum =0;for (int i = 1; i <=n ; i++) {sum += i;}return "线程所求之和为"+sum;}
}
注意事项: