21xrx.com
2024-09-17 04:07:02 Tuesday
登录
文章检索 我的文章 写文章
——多线程编程
2023-06-14 23:49:49 深夜i     --     --
JavaSE 多线程编程 Thread类

JavaSE是Java的标准版,是Java编程语言的核心,面向桌面和服务端应用。JavaSE的进阶涉及到多个方面,其中之一就是多线程编程。多线程编程是指在同一时间内开启多个线程执行不同的任务,提高程序效率的同时也增加了程序的复杂性。

JavaSE中的多线程编程是通过Thread类和Runnable接口实现的。Thread类是 Java 唯一内置的线程管理对象。下面是一个简单的多线程编程案例:


public class MyThread implements Runnable {

  private String threadName;

  

  MyThread(String name) {

    threadName = name;

    System.out.println("Creating " + threadName);

  }

  

  public void run() {

    System.out.println("Running " + threadName);

    try {

      for(int i = 4; i > 0; i--) {

        System.out.println("Thread: " + threadName + ", " + i);

        Thread.sleep(50);

      }

    } catch (InterruptedException e) {

      System.out.println("Thread " + threadName + " interrupted.");

    }

    System.out.println("Thread " + threadName + " exiting.");

  }

  

  public void start() {

    System.out.println("Starting " + threadName);

    Thread t = new Thread(this, threadName);

    t.start();

  }

}

public class Main {

  public static void main(String args[]) {

    MyThread thread1 = new MyThread("Thread-1");

    thread1.start();

    MyThread thread2 = new MyThread("Thread-2");

    thread2.start();

  }

}

上述代码定义了MyThread类实现了Runnable接口,在run方法中定义了线程的具体执行内容。在Main类中,创建了两个线程,分别启动。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复