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)。

  • 相关阅读:
    结构体运算符重载出错分析
    已知空间三个点,解算外接圆圆心坐标,C++编程实现
    IQueryable与IEnumberable的区别
    Asp.net MVC中关于@Html标签Label、Editor使用
    MVC 基架不支持 Entity Framework 6 或更高版本 即 NuGet的几个小技巧
    MVC下拉框Html.DropDownList 和DropDownListFor 的常用方法
    js jq封装ajax方法
    httpSession的正确理解
    vs未能解析此远程名称: 'api.nuget.org'
    未能加载文件或程序集“EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”
  • 原文地址:https://www.cnblogs.com/james1207/p/3279872.html
Copyright © 2011-2022 走看看