image.pngimage.pngimage.png

线程使用

image.pngimage.pngimage.png
image.png

  1. class Hi implements Runnable {
  2. int times= 0;
  3. @Override
  4. public void run() {
  5. while (true){
  6. try {
  7. Thread.sleep(1000);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. System.out.println("hi"+(++times));
  12. if (times == 10){
  13. break;
  14. }
  15. }
  16. }
  17. public static void main(String[] args) {
  18. Hi hi = new Hi();
  19. //创建thread对象
  20. Thread thread = new Thread(hi);
  21. thread.start();
  22. }
  23. }

image.png
image.png
image.png

线程的终止

image.png

  1. public class Exit {
  2. public static void main(String[] args) {
  3. T t = new T();
  4. t.start();
  5. try {
  6. System.out.println("休眠5s...");
  7. Thread.sleep(10*500);
  8. t.setLoop(false);//设置loop的值
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. }
  13. }
  14. class T extends Thread{
  15. private int count = 0;
  16. //设置一个boolean 类型的对象,后面好赋值条件
  17. private Boolean loop = true;
  18. //提供set方法给loop赋值
  19. public void setLoop(Boolean loop) {
  20. this.loop = loop;
  21. }
  22. @Override
  23. public void run() {
  24. while (loop){
  25. System.out.println("T 运行中....");
  26. try {
  27. Thread.sleep(100);
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. }

线程的常用方法

image.png
image.png
image.png
image.png
image.png

线程生命周期

image.png

线程同步

image.png

互斥锁

image.png