zoukankan      html  css  js  c++  java
  • SummerVocation_Learning--java的多线程实现

    java的线程是通过java.lang.Thread类来实现的。

         可以通过创建Thread的实例来创建新的线程。

         每个线程都是通过某个特定Thread对象所对应的方法run()来完成操作,方法run()称为线程体。

         通过调用Thread类的start()方法来启动一个线程。

         线程的创建和启动方式:

                 1.  定义线程类实现Runnable接口。

                      Thread t = new Thread(Runnable target) //target为Runnable接口类型。

                      Runnable中只有一个方法: public void run();用以定义线程运行体。

                      使用Runnable接口可以为多个线程提供共享数据。

                      在实现Runnable接口的类的run方法定义中可以使用Thread的静态方法。

                      public static Thread currentThread()获取当前线程的引用。

              2.  可以定义一个Thread的子类并重写run()方法,如:

                      class MyThread extends Thread {

                               public void run() {...}

                       }

                 然后生成该类的对象: MyThread t = new MyThread(...); 

     1 import java.lang.Thread; //导入线程实现包
     2  
     3 public class Test_Thread {
     4  
     5     public static void main(String[] args) {
     6         Runner1 r = new Runner1();
     7         
     8         Thread t = new Thread(r); //启动线程要new一个Thread对象。此处其target为r
     9         t.start();
    10         
    11         for (int i = 0; i <= 50; i++) {
    12             System.out.println("Main Thread: " + i);
    13         }
    14     }
    15     /*
    16      *
    17 Main Thread: 0
    18 Main Thread: 1
    19 Main Thread: 2
    20 Main Thread: 3
    21 Main Thread: 4
    22 Main Thread: 5
    23 Runner1: 0
    24 Runner1: 1
    25 Runner1: 2
    26 Runner1: 3
    27 Runner1: 4
    28 Main Thread: 6
    29 Runner1: 5
    30 Runner1: 6
    31 Runner1: 7
    32 Main Thread: 7
    33 Runner1: 8
    34 ...
    35 Main Thread: 50
    36 Runner1: 50
    37      */
    38 }
    39  
    40 class Runner1 implements Runnable{
    41     public void run() {
    42         for (int i = 0; i <= 50; i++) {
    43             System.out.println("Runner1: " + i);
    44         }
    45     }
    46 }
  • 相关阅读:
    chrome的console功能
    vue-cli · Failed to download repo vuejs-templates/webpack: connect ETIMEDOUT 13.229.188.59:443
    let const区别!
    字符串拼接事故!
    git常用的操作命令
    vue项目中利用popstate处理页面返回操作
    Mac下安装nginx并配置SSL实现Https的访问
    浏览器缓存
    HTTP相关知识点
    CORS请求
  • 原文地址:https://www.cnblogs.com/DSYR/p/9320979.html
Copyright © 2011-2022 走看看