zoukankan      html  css  js  c++  java
  • Java 线程(一)

    interrupt () 可以终止线程,略显粗暴。(比起stop() 还是温柔一些 = = .orz )

    介绍一种不用interrupt()终止线程的方法。

    public class TestThread4{
        public static void main(String []args) {
            Runner4 r = new Runner4();    //创建实现了Runnable Interface的类的实例
            Thread t = new Thread(r);    //根据Thread Constructor ,传入Runnable 参数。此处有多态(父类引用指向子类,该处为接口类型指向实现接口的类,重写,实现)
            t.start();        //Thread.start()会自动调用传入Runnable Obj 的 run()   此语句,t 和 main 两个Thread 运行
            for(int i=0; i<10000; i++) {
                if(i % 1000 ==0 & i > 0){
                    System.out.println("in thread main i =" + i);
                }
            }
            System.out.println("Thread main is over");
            r.shutDown();  //当main执行完后,调用实现Runnable Interface的shutDown()来终止Thread t 
        }
    }
    
    class Runner4 implements Runnable {
        private boolean flag = true;    
        public void run(){
            int i = 0;
            while(flag == true){    //run()运行的条件为flat == true , run()条件不满足,run()结束,Thread结束
                System.out.println(" " + i++);
            }
        }
        public void shutDown(){
            flag = false;    //修改boolean 使run()结束
        }
    }

    in thread main i =1000
     0
    in thread main i =2000
     1
     2
     3
    in thread main i =3000
     4
    in thread main i =4000
     5
     6
     7
     8
     9
     10
     11
    in thread main i =5000
    in thread main i =6000
     12
     13
    in thread main i =7000
    in thread main i =8000
     14
     15
    in thread main i =9000
     16
    Thread main is over
     17
    View Code

    内存布局如图所示:

  • 相关阅读:
    Kibana: missing authentication credentials for REST request
    MySQL命令速记
    VIM常用命令简记
    Linux常用命令简记
    袁永福的C#编程书籍,电子工业出版社出版。
    发布DCWriter电子病历文本编辑器
    袁永福的博客系列文章链接集合
    ssh隧道 的命令行和 sshd 服务的配置(gatePort)
    PureMVC(AS3)剖析:设计模式(二)
    Python应用与实践
  • 原文地址:https://www.cnblogs.com/leafh/p/8863417.html
Copyright © 2011-2022 走看看