通过调用Thread类的start()方法来启动一个线程,这时此线程是处于就绪状态,并没有运行。
然后通过此Thread类调用方法run()来完成其运行操作的,
这里方法run()称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程终止,
而CPU再运行其它线程,
Deamon:守护进程
- public class TestThread {
- public static void main(String[] args) {
- Thread1 t = new Thread1();
- Thread c = new Control(t);
- t.setSleep(true);
- c.setDaemon(true);
- t.start();
- c.start();
- System.out.println("You can input 'g' and 'Enter' to start your job.");
- System.out.println("You can input 'w' and 'Enter' to let your job to wait...");
- System.out.println("You can input 's' and 'Enter' to finish your job.");
- }
- }
- class Thread1 extends Thread {
- private boolean isSleep = true;
- private boolean isStop = false;
- public void run() {
- while(!isStop) {
- if(isSleep) {
- try {
- Thread.sleep(1);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("Thread: "+Thread.currentThread().getName() + " do someting.");
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- System.out.println("Thread: "+Thread.currentThread().getName() + " finished.");
- }
- public void setSleep(boolean sleep) {
- this.isSleep = sleep;
- }
- public void setStop(boolean stop) {
- this.isStop = stop;
- }
- }
- class Control extends Thread {
- private Thread1 t;
- public Control(Thread1 t) {
- this.t = t;
- }
- public void run() {
- while(true) {
- int r=0;
- try {
- r=System.in.read();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if(r == 'g') {
- t.setSleep(false);
- } else if(r == 'w') {
- t.setSleep(true);
- } else if(r == 's') {
- t.setStop(true);
- }
- }
- }
- }
程序说明:
1,刚开始程序的等待的。
2,你输入‘g’回车后会运行。
3,你输入‘w’回车后会再次等待。
4,再次输入‘g’回车后又会运行。
5,输入‘s'回车,会终止程序。
6,这里将控制线程设置成了Deamon的形式,因为线程t由线程c控制可以终止,而线程c始终无法终止,所以把它设置为后台线程,当让控制的线程t退出时,所有的前台线程都结束了,这样线程c就可以自动退出。