当前位置:   article > 正文

Java线程的两种实现方式(Rundable接口和lambda)_lamda 创建线程 java 传入参数

lamda 创建线程 java 传入参数

 

  1. package com.it;
  2. /**
  3. * 通过Runnable接口创建线程
  4. */
  5. public class TestThread01 implements Runnable {
  6. @Override
  7. public void run() {
  8. for (int i = 0; i < 10; i++) {
  9. System.out.println(Thread.currentThread().getName()+":"+i);
  10. }
  11. }
  12. public static void main(String[] args) {
  13. TestThread01 t = new TestThread01();
  14. // 把实现了Runnable接口的对象作为参数传入
  15. Thread t1 = new Thread(t);
  16. t1.start();
  17. Thread t2 = new Thread(t);
  18. t1.start();
  19. }
  20. }
  1. package com.it;
  2. /**
  3. * 使用lambda表达式创建线程
  4. */
  5. public class TestThread02 {
  6. public static void main(String[] args) {
  7. // 通过匿名内部类的方式创建线程
  8. new Thread(new Runnable() {
  9. @Override
  10. public void run() {
  11. for (int i = 0; i < 10; i++) {
  12. System.out.println(Thread.currentThread().getName()+":"+i);
  13. }
  14. }
  15. }).start();
  16. new Thread(()->{
  17. for (int i = 0; i < 10; i++) {
  18. System.out.println(Thread.currentThread().getName()+":"+i);
  19. }
  20. }).start();
  21. }
  22. }
  1. package com.it;
  2. /**
  3. * 测试终止线程的典型方法
  4. */
  5. public class TestThreadCycle_Terminated implements Runnable{
  6. boolean live = true;//标记线程是否可以结束
  7. @Override
  8. public void run() {
  9. int i =0;
  10. while(live){
  11. System.out.println(Thread.currentThread().getName()+":"+i++);
  12. }
  13. }
  14. public void terminate(){
  15. live = false;
  16. }
  17. public static void main(String[] args) {
  18. TestThreadCycle_Terminated tt = new TestThreadCycle_Terminated();
  19. Thread t = new Thread(tt);//新生状态
  20. t.start();//就绪状态
  21. for (int i = 0; i < 10; i++) {
  22. System.out.println("主线程"+i);
  23. }
  24. tt.terminate();//结束线程
  25. System.out.println("tt线程结束");
  26. }
  27. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/974803
推荐阅读
相关标签
  

闽ICP备14008679号