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

  • 相关阅读:
    工厂模式
    Bootstrap 日历
    处理乱码
    Eclipse常用快捷键
    C#_XML与Object转换
    jQuery选择函数
    Bootstrap如何正确引用字体图标
    js上拉加载、下拉刷新的插件
    js通用对象数组冒牌排序
    关于js跨域
  • 原文地址:https://www.cnblogs.com/james1207/p/3279872.html
Copyright © 2011-2022 走看看