Home  >  Article  >  Java  >  Detailed explanation of java threads and the difference between threads and processes

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

高洛峰
高洛峰Original
2017-01-19 11:25:461453browse

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