search
HomeJavajavaTutorialDetailed explanation of java threads and the difference between threads and processes

java Detailed explanation of threads and the difference between threads and processes

1. Processes and threads

Each process has its own memory space, and one application can start multiple processes at the same time. For example, with IE browser, opening an IE browser is equivalent to starting a process.

Thread refers to an execution process in a process. A process can contain multiple threads.

Each process requires the operating system to allocate independent memory space for it, and multiple threads in the same process share this space, that is, shared memory and other resources.

Every time java.exe is called, the operating system will start a Java virtual machine process. When the Java virtual machine process is started, the Java virtual machine will create a main thread, which will start from the program entry main method. Begin execution.

Every time a Java virtual machine starts a thread, it will allocate a thread method stack to the thread to store relevant information (such as local variables, etc.), and the thread will run on this stack. Therefore, local variables in Java objects are thread-safe, but instance variables and class variables are not thread-safe because they are not saved on the stack.

The process has three states: ready, executing, and blocked.

Detailed explanation of java threads and the difference between threads and processes

2. Thread creation method

Runnable method: (This method is flexible and recommended)

public class Thread02 implements Runnable {
  
  public static void main(String[] args) {
    Runnable r = new <strong>Thread02</strong>();
    Thread t1 = new Thread(<strong>r</strong>, "t1");
    /**
     *   Thread源码
     *   public Thread(Runnable target, String name) {
          init(null, target, name, 0);
             }
     */
    Thread t2 = new Thread(r, "t2");
    t1.start(); // 启动线程t1,处于就绪状态,等待cpu
    t2.start(); // 启动线程t2,处于就绪状态,等待cpu
    t1.run(); // 主线程main调用对象t1的run方法
  }
  
  public void run() {
    System.out.println("thread&#39;s name is "
        + Thread.currentThread().getName());
  }
  
}

The running result may be:

thread&#39;s name is t1
thread&#39;s name is main
thread&#39;s name is t2

Thead way

public class Thread03 extends Thread {
  
  public static void main(String[] args) {
    Thread03 t1 = new <strong>Thread03</strong>();   //不注意的情况下写成了Thread t1=new Thread()  注:Thread03此时就是一个线程了
    t1.start();
  }
  
  public void run() {
    System.out.println("thread&#39;s name is "
        + Thread.currentThread().getName());
  }
}

The running result: thread's name is Thread-0

Note: Every time the program runs, there is a main thread in addition to the custom thread.

Comprehensive:

public class Thread01 {
  public static void main(String[] args) {
 
    Thread thread=new Thread();
    thread.start();//真正起作用 的是run()
    /**而Thread中的run
     * public void run() {
      if (target != null) {
        target.run();
      }
      }
      所以自己创建的线程要重写run方法,把要执行的内容放到run()中,所以要实现接口或继承进而产生子类
     */
     
    //创建线程的方式1 thread子类方式(继承)
    Thread thread1=new Thread(){
      public void run() {
        while(true){
          try {
            Thread.sleep(500);//休息500毫秒
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          //Thread.currentThread()得到当前线程
          System.out.println("线程1的名字是 "+Thread.currentThread().getName());
        }
      }
    };
//    thread1.start(); //不写  线程无法启动
     
     
    //创建线程的方式2 runnable方式(实现) 推荐使用
    Thread thread2=new Thread(new Runnable(){
 
      public void run() {
 
        while(true){
          try {
            Thread.sleep(300);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println("thread2&#39;name is "+Thread.currentThread().getName());
           
        }
      }});
//    thread2.start();
     
    //执行的是thread
    new Thread(new Runnable(){
      public void run() {
        System.out.println("runnable "+Thread.currentThread().getName());
      }}){
      public void run() { //子类中的run方法覆盖父类中的run方法,这样就不会执行runnable
        System.out.println("thread "+Thread.currentThread().getName());
      }
    }.start();
  }
  /***
   * 在单个cpu中执行多线程很有可能降低执行效率而不是提高 一个人在不同地方做同一件事情
   */
}

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more detailed explanations of Java threads and related articles on the difference between threads and processes, please pay attention to the PHP Chinese website!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!