(36)线程实现的两种方式

进程与线程:

进程-- 一个应用程序可以启动一个进程,也可以启动多个进程。JVM会在内存中为进程分配独立的运行空间。

线程-- 进程内部的独立空间,有自己的内存空间和栈(保存局部变量)。

编写服务器时要使用到多线程,因为要服务多个客户端。、

多线程:一个进程中,我们同时开启多个线程,让多个线程同时去完成某些任务(功能)。

现在的操作系统基本都是多用户,多任务的操作系统。每个任务就是一个进程。在这个进程中就会有线程。

真正可以完成程序运行和功能的实现靠的是进程中的线程。

(比如后台服务系统,就可以用多个线程同时响应多个客户的请求)

多线程的目的:提高程序的运行效率。

多线程运行的原理:

cpu在线程中做时间片的切换。

其实真正电脑中的程序的运行不是同时在运行的。CPU负责程序的运行,而CPU在运行程序的过程中某个时刻点上,它其实只能运行一个程序。不是多个程序。而CPU它可以在多个程序之间进行高速的切换。切换频率和速度太快,导致人的肉看不到。

每个程序就是进程, 每个进程中会有多个线程,而CPU是在这些线程之间进行切换。

了解CPU对一个任务的执行过程,我们就必须知道,多线程可以提高程序的运行效率,但不能无限制的开线程。

java中实现线程的两种方式:

(1)继承Thread

import java.util.Random;

public class MyThreadWithExtends extends Thread {
       String flag;

       public MyThreadWithExtends(String flag){
              this.flag = flag;
       }

      @Override
      public void run() {
             String tname = Thread.currentThread().getName();
             System.out.println(tname+"线程的run方法被调用……");
             Random random = new Random();
             for(int i=0;i<20;i++){
                    try {
                          Thread.sleep(random.nextInt(10)*100);
                          System.out.println(tname+ "...."+ flag);
                          } catch (InterruptedException e) {
                                 e.printStackTrace();
                          }
                      }
      }

      public static void main(String[] args) {
             Thread thread1 = new MyThreadWithExtends("a");
             Thread thread2 = new MyThreadWithExtends("b");
             thread1.start();  //开启新的线程
             thread2.start();
             /*
             * 如果是调用thread的run方法,则只是一个普通的方法调用,不会开启新的线程
             */
            // thread1.run();
            // thread2.run();
      }
}

(2)声名实现Runnable接口


public class MyThreadWithImpliment implements Runnable {
       int x;

       public MyThreadWithImpliment(int x) {
             this.x = x;
       }

       @Override
       public void run() {
              String name = Thread.currentThread().getName();
              System.out.println("线程" + name + "的run方法被调用……");
              for (int i = 0; i < 10; i++) {
                    System.out.println(x);
              try {
                    Thread.sleep(100);
                   } catch (InterruptedException e) {
                          e.printStackTrace();
                   }
               }
       }

       public static void main(String[] args) {
              Thread thread1 = new Thread(new MyThreadWithImpliment(1), "thread-1");
              Thread thread2 = new Thread(new MyThreadWithImpliment(2), "thread-2");
              thread1.start();
              thread2.start();
              // 注意调用run和调用start的区别,直接调用run,则都运行在main线程中
              // thread1.run();
              // thread2.run();
       }
}

原文地址:https://www.cnblogs.com/paradis/p/11429594.html