1.继承Thread类创建多线程
步骤:创建类继承Thread类,覆盖run()方法,创建对象,调用start方法启动线程
例:
package Multithreading.Thread; //多线程的启动方式 //1.继承Thread类 覆盖run()方法 创建对象 调用start方法 //注意:start()方法表示开启线程 public class MyThread extends Thread { public void run(){ for (int i = 0; i <=100 ; i++) { System.out.println(getName() + "helloworld"); } } }
package Multithreading.Thread; public class Demo1 { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.setName("线程1"); t2.setName("线程2"); t1.start(); t2.start(); } }
2.实现Runnable接口创建多线程
步骤:①定义类实现Runable接口
②重写run()方法
③创建自己类的对象
④创建Thread类的对象(参数为自己类的对象),并开启线程
例:
package Multithreading.Runnable; //Runnable 接口 实现类启动多线程 /* 1.定义类实现Runnable接口 2.重新run方法 3.创建自己类的对象 4.创建Thread类的对象参数为自己类的对象,并开启线程 */ public class MyRunnable implements Runnable{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+"helloworld"); } } }
package Multithreading.Runnable; public class Demo1 { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t1 = new Thread(mr); Thread t2 = new Thread(mr); t1.setName("线程1"); t2.setName("线程2"); t1.start(); t2.start(); } }
3.使用 Callable 和 Future 接口创建对象
特点:能获取多线程的结果
步骤:①.创建一个类MyCallable实现Callable接口
②.重写call方法(有返回值,返回结果为多线程运行的结果)
③.创建MyCallable的对象(表示多线程要执行的任务)
④.创建FutureTask的对象(管理多线程运行的结果)
⑤.创建Thread类的对象,并启动(表示线程)
例:
package Multithreading.Third; import java.util.concurrent.Callable; //定义类实现Callable接口 //注意:Callable接口自带泛型<V>,如果自己不定义泛型类型则会默认为Object类型 //重写出来的方法默认为Object方法 //我要求100以内的整数总和sum public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i < 100; i++) { sum = sum + i; } return sum; } }
package Multithreading.Third; import java.util.concurrent.FutureTask; public class Demo1 { /* 多线程的第三种写法: 1.创建一个类MyCallable实现Callable接口 2.重写call方法(有返回值,返回结果为多线程运行的结果) 3.创建MyCallable的对象(表示多线程要执行的任务) 4.创建FutureTask的对象(管理多线程运行的结果) 5.创建Thread类的对象,并启动(表示线程) */ public static void main(String[] args) throws Exception { //创建MyCallable类的对象 MyCallable mc = new MyCallable(); //创建FutureTask类的对象管理多线程的结果 FutureTask<Integer> ft = new FutureTask<>(mc); //创建线程对象 Thread t = new Thread(ft); //启动线程 t.start(); //获取多线程的结果 Integer result = ft.get(); System.out.println(result); } }