一、线程对象的基本操作

image.png

二、获取线程对象

image.png

  1. package com.bjpowernode.java.thread;
  2. public class ThreadTest04 {
  3. public static void main(String[] args) {
  4. Thread currentThread = Thread.currentThread();
  5. System.out.println(currentThread.getName());
  6. //创建线程对象
  7. MyThread2 t1 = new MyThread2();
  8. //设置名字
  9. t1.setName("t1");
  10. //获取线程名字
  11. System.out.println(t1.getName());
  12. MyThread2 t2 = new MyThread2();
  13. t2.setName("t2");
  14. t2.start();
  15. t1.start();
  16. for (int i=0;i<100;i++){
  17. System.out.println(currentThread.getName()+"-->"+i);
  18. }
  19. }
  20. }
  21. class MyThread2 extends Thread{
  22. @Override
  23. public void run() {
  24. for (int i=0;i<1000;i++){
  25. Thread currentThread = Thread.currentThread();
  26. System.out.println(currentThread.getName()+"-->"+i);
  27. }
  28. }
  29. }

三、sleep方法

重点静态方法,让当前线程进入休眠
image.png

  1. package com.bjpowernode.java.thread;
  2. /*
  3. 面试题
  4. */
  5. public class ThreadTest07 {
  6. public static void main(String[] args) {
  7. Thread t = new MyThread3();
  8. t.setName("t");
  9. t.start();
  10. try {
  11. //这行代码会让线程t进入休眠吗?
  12. //不会,让当前线程main进入休眠
  13. t.sleep(1000 * 5);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }
  19. class MyThread3 extends Thread{
  20. @Override
  21. public void run() {
  22. for (int i=0;i<1000;i++){
  23. System.out.println(Thread.currentThread().getName()+"--->"+i);
  24. }
  25. }
  26. }

四、终止线程

1.stop()——过时

image.png
image.png

2.true和false

  1. package com.bjpowernode.java.thread;
  2. public class ThreadTest10 {
  3. public static void main(String[] args) {
  4. MyRunnable4 r = new MyRunnable4();
  5. Thread t = new Thread(r);
  6. t.setName("t");
  7. t.start();
  8. //等5秒
  9. try {
  10. Thread.sleep(1000*5);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. //终止线程
  15. r.run = false;
  16. }
  17. }
  18. class MyRunnable4 implements Runnable{
  19. boolean run = true;
  20. @Override
  21. public void run() {
  22. for (int i=0;i<10;i++){
  23. if (run){
  24. System.out.println(Thread.currentThread().getName()+"--->"+i);
  25. try {
  26. Thread.sleep(1000);
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. }else {
  31. return;
  32. }
  33. }
  34. }
  35. }