zoukankan      html  css  js  c++  java
  • 多线程(1)--基础实现

    //多线程操作类 继承Thread类
    public class TestThread extends Thread {
        private String name;//共享变量
        public TestThread(String name){
                this.name=name;
        }
        public void run(){
                for(int i = 0 ;i<100;i++){
                         System.out.println(this.name);
                }
        }
    }

    //主线程
    public class MainThread {

          /**
           * @param args
          */
          public static void main(String[] args) {
                 new TestThread("shixin").start();
                 new TestThread("axue").start();

          }

    }

    //多线程操作类 继承Runnable接口
    public class TestThread implements Runnable{
          private String name;//共享变量
          public TestThread(String name){
                this.name=name;
          }
          public void run(){
                for(int i = 0 ;i<100;i++){
                System.out.println(this.name);
                }
          }
    }
    //主线程

    public class MainThread {

        /**
        * @param args
        */
        public static void main(String[] args) {
            new Thread(new TestThread("shixin")).start();
            new Thread(new TestThread("axue")).start();

        }

    为什么要用start()方法启动多线程呢?

    在JDK的安装目录下,src.zip是全部的java源程序,通过此代码找到Thread类的Thread方法的定义:

    public synchronized void start(){
          if(started)//判断多线程是否已启动
                 throw new IllegalThreadStateException;
         started = true;
         start0();//调用start0()方法
     }
        private native void start0();//使用native关键字声明的方法,没有方法体

    操作系统有很多种,Windows、Linux、Unix,既然多线程操作中要进行CPU资源的强占,也就是说要等待CPU调度,那么这些调度的操作时由各个操作系统的底层实现的,所以在Java程序中根本就没法实现,那么此时Java设计者定义了native关键字,使用此关键字表示可以调用操作系统的底层函数,那么这样的技术又称为JNI技术(Java Native Interface)。

  • 相关阅读:
    Hitachi Programming Contest 2020 E Odd Sum Rectangle
    CF1060F Shrinking Tree
    UR #19
    AGC041F Histogram Rooks
    JOISC2020 Legendary Dango Maker
    Dinic 二分图匹配 / Hopcroft-Karp 算法 复杂度简单证明
    Codechef March Challenge 2020 Division 1 BREAK
    Tomorrow will be fine.
    JOISC2019 穿越时空 Bitaro
    POI2011 Periodicity
  • 原文地址:https://www.cnblogs.com/james1207/p/3279872.html
Copyright © 2011-2022 走看看