线程的启动和停止

import java.lang.Thread;
import java.lang.Runnable;
import java.util.Date;

public class DefineAndStartThread{
class ThreadA extends Thread{
private Date runDate;
//继承Thread的子类必须实现run方法,Thread中的run方法未做任何事
public void run(){
System.out.println("ThreadA begin");
this.runDate = new Date();
System.out.println("ThreadA run: "+this.runDate);
System.out.println("ThreadA end");
}
}

class ThreadB implements Runnable{
private Date runDate;
public void run(){
System.out.println("ThreadB begin");
this.runDate = new Date();
System.out.println("ThreadB run: "+this.runDate);
System.out.println("ThreadB end");
}
}

public void startThreadA(){
//这里是面向对象的多态特征,子类对象可以直接赋给父类变量,但运行时依然表现为子类特性
//声明变量类型为父类,实际变量类型为子类对象
Thread threadA = new ThreadA();
//启用线程后,jvm会调用该线程的run方法,执行线程
threadA.start();
}

public void startThreadB(){
Runnable rb = new ThreadB();
Thread threadB = new Thread(rb);
//启用线程后,会引起调用该线程的run方法,执行线程
threadB.start();
}

public static void main(String[] args){
DefineAndStartThread test = new DefineAndStartThread();
test.startThreadA();
test.startThreadB();
}
}

import java.lang.Thread;
import java.util.Date;

public class StopThread{
    //因为该类的start、stop、main方法都要用到ThreadA的实例对象,所以声明为类变量
    private ThreadA thread = new ThreadA();
    class ThreadA extends Thread{
        //用来对外设置是否执行run方法的标识
        private boolean running = false;
        private Date runDate;
        //重写Thread父类的start方法,在父类start方法之上设置运行标识为true
        public void start(){
            this.running = true;
            super.start();
            }
        //线程一旦启动则不停的循环执行,直到执行标识为false,则停止运行
        public void run(){
            System.out.println("ThreadA begin");
            try{
                int i=0;
                while(this.running){
                this.runDate = new Date();
//                System.out.println("ThreadA run: "+this.runDate);
                System.out.println("ThreadA run: "+ i++);
                Thread.sleep(200);
                }
            }catch(InterruptedException e){
                e.printStackTrace();
                }
            System.out.println("ThreadA end");
            }
            
        public void setRunning(boolean running){
            this.running = running;
            }
        }
        
        public void start(){
            this.thread.start();
            }
        
        //修改执行标识为false则停止执行run方法    
        public void stop(){
            this.thread.setRunning(false);
            }
        public static void main(String[] args){
            StopThread stopThread = new StopThread();
            //线程一直运行直到结果结束
            stopThread.start();
            //当前线程休眠1秒
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
                }
            stopThread.stop();
            }
    
    }
原文地址:https://www.cnblogs.com/celine/p/9460536.html