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

    内存布局如图所示:

  • 相关阅读:
    【Access2007】将Excel表导入到Access2007在现有的表成
    IntentFilter
    C++ map
    C++ template
    c++ namespace
    JVM学习笔记
    hibernate配置文件hibernate.cfg.xml的详细解释
    以&运行在后台的程序,关闭terminal后,相应进进程自动关闭
    开市前挂单
    Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里
  • 原文地址:https://www.cnblogs.com/leafh/p/8863417.html
Copyright © 2011-2022 走看看