线程创建
线程创建的三种方式:
1.继承Thread类
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//总结:线程开启不一定立即执行,由cpu调度
public class Thread1 extends Thread{ @Override public void run() { //run方法 for (int i = 0; i <20 ; i++) { System.out.println("我在看代码---"+ i); } } public static void main(String[] args) { //main线程,主线程 //创建一个线程对象 Thread1 thread1 = new Thread1(); //调用start开启线程 thread1.start(); for (int i = 0; i <20 ; i++) { System.out.println("我在学习多线程-----" +i); } } }
2.实现Runnable接口
//创建线程方式二:实现runnable接口,重写run()方法,执行线程需要丢入runnable实现类,调用start方法 public class Thread2 implements Runnable { @Override public void run() { //run方法 for (int i = 0; i <20 ; i++) { System.out.println("我在看代码---"+ i); } } public static void main(String[] args) { //main线程,主线程 //1.创建实现runnable接口实现对象 Thread2 thread2 = new Thread2(); //2.创建线程对象,通过线程对象来开启我们的线程,代理 Thread thread = new Thread(thread2); //调用start开启线程 thread.start(); for (int i = 0; i <20 ; i++) { System.out.println("我在学习多线程-----" +i); } } }
3.实现Callable接口
//线程创建方式三:实现Callable接口,第一步先实现Callable重写call方法,第二步创建线程对象 // 第三步创建执行服务,第四步提交执行,第五步获取结果,最后一步关闭服务。 /** *好处: * 1.可以定义返回值 * 2.可以抛出异常 */ public class Thread5 implements Callable<Boolean> { private Integer ticketNums =10; @Override public Boolean call() { while (true){ if (ticketNums<=0){ break; } System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票"); } return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { Thread5 t1 = new Thread5(); Thread5 t2 = new Thread5(); Thread5 t3 = new Thread5(); //创建执行服务 ExecutorService service = Executors.newFixedThreadPool(3); //提交执行 Future<Boolean> s1 = service.submit(t1); Future<Boolean> s2 = service.submit(t2); Future<Boolean> s3 = service.submit(t3); //获取结果 Boolean i1 = s1.get(); Boolean i2 = s2.get(); Boolean i3 = s3.get(); System.out.println(i1); System.out.println(i2); System.out.println(i3); //关闭服务 service.shutdown(); } }
浙公网安备 33010602011771号