Java笔记15:多线程

时间:2025-03-16 15:05:37

Java实现多线程有两种方式:一是继承Thread类;二是实现Runable接口。

一、Thread实现

  1. publicclass ThreadDemo2 {
  2. publicstaticvoid main(String[] args) {
  3. new TestThread2().start();
  4. inti = 0;
  5. while(i++ < 100) {
  6. System.out.println("main thread is running");
  7. }
  8. }
  9. }
  10. class TestThread2 extends Thread {
  11. publicvoid run() {
  12. intj = 0;
  13. while(j++ < 100) {
  14. System.out.println(Thread.currentThread().getName() + " is running!");
  15. }
  16. }
  17. }

运行结果:

Java笔记15:多线程

二、Runnable实现

  1. publicclass ThreadDemo3 {
  2. publicstaticvoid main(String[] args) {
  3. TestThread3 t3 = new TestThread3();
  4. Thread t = new Thread(t3);
  5. t.start();
  6. inti = 0;
  7. while(i++ < 100) {
  8. System.out.println("main thread is running");
  9. }
  10. }
  11. }
  12. class TestThread3 implements Runnable {
  13. publicvoid run() {
  14. intj = 0;
  15. while(j++ < 100) {
  16. System.out.println(Thread.currentThread().getName() + " is running!");
  17. }
  18. }
  19. }

运行结果:

Java笔记15:多线程