课堂笔记--多线程相关补充

中断线程与定时器应用
本文详细介绍了Java中如何使用interrupt()方法设置线程中断标记及其实现方式,同时结合Timer和TimerTask展示了定时任务的实现。通过实例代码演示了中断线程与定时器的应用场景。
 

中断线程的应用

interrupt()方法:

实际上该方法不会中断正在执行的线程,只是将线程的标志位设置成true(可以用isInterrupted()方法测试该线程的中断标记,并不清除中断标记,static的方法interrupted()测试当前执行的线程是否被中断,并且在肯定的情况下,清除当前线程对象的中断标记并返回true);

如果线程在调用sleep(),join(),wait()方法时线程被中断,则这些方法会抛出InterruptedException,在catch块中捕获到这个异常时,线程的中断标志位已经被设置成false了 。

注意:

Interrupt()方法只是为线程设置了一个中断标记,并没有中断线程运行。一个线程在被设置了中断标记之后仍可运行,isAlive()返回true。实例方法isInterrupted()测试线程的中断标记,并不清除中断标记。而静态的interrrupted()方法不同,他会测试当前执行的线程是否中断,并且在坑定的情况下,清除当前线程对象的中断标记并返回true。

 

可通过下面一段简单的代码去理解interrrupt()方法:

public class testTime {

    /**

     * @param args

     */

    public static void main(String[] args) {

       // TODO Auto-generated method stub

       InterruptThread t1 = new InterruptThread();

       t1.start();

       for (int i = 0; i < 5; i++) {

           System.out.println("main" + i);

       }

       t1.interrupt();

       System.out.println("main" + t1.isInterrupted());

    }

 

}

 

class InterruptThread extends Thread{

    public void run(){

       System.out.println(this.isAlive());//测试线程是否运行 true

       System.out.println(this.isInterrupted());//测试线程是否有中断标记    false

       this.interrupt();//给线程设置中断标记

       System.out.println(this.isAlive());//测试线程是否运行true

       System.out.println(this.isInterrupted());//测试线程是否有中断中断标记  true

       for(int i=0;i<5;i++){

           System.out.println("子线程"+i);

           try {

              Thread.sleep(1000);

           } catch (InterruptedException e) {

              // TODO Auto-generated catch block

              System.out.println("子"+this.isInterrupted());//测试线程是否有中断中断标记   false

              return;

           }

       }

    }

}

 

定时器:Timer和TimerTask

前面已经提到实现多线程的方式有三种:

继承Thread类

实现Runnable接口

使用Timer和TimerTask组合

前两种已经在前面介绍过了,现在补充一下第三种方式。

 

java.util包中的Timer和TimerTask类也可实现多线程

Timer类实现的是类似闹钟的功能,也就是定时或者每隔一定时间间隔触发一次线程。

TimerTask类是一个抽象类,该类实现了Runnable接口,具备多线程的能力。

通过继承TimerTask类创建子类,使该子类获得多线程的能力,将需要多线程执行的代码书写在run方法内部,然后通过Timer类启动线程的执行。

 

实例,使用Timer和TimerTask组合实现的多线程。

 package com.hbsi.thread;

 

import java.util.*;

 

public class testTime {

    public static void main(String[] args) {

       // 创建Timer

       Timer t = new Timer();

       // 创建TimerTask

       TimerTask1 tt1 = new TimerTask1();

       // 启动线程

       t.schedule(tt1, 0);

       try {

           for (int i = 0; i < 5; i++) {

              Thread.sleep(1000);

              System.out.println("Main:" + i);

           }

       } catch (Exception e) {

       }

    }

}

 

/* 以继承TimerTask类的方式实现多线程 */

class TimerTask1 extends TimerTask {

    public void run() {

       try {

           for (int i = 0; i < 5; i++) {

              Thread.sleep(1000);

              System.out.println("Run" + i);

           }

       } catch (Exception e) {

       }

    }

}

schedule()方法的应用

1.  public void schedule(TimerTask task,Date time):该方法的作用是在到达time指定的时间或已经超过该时间时执行线程task。
Date d = new Date(2009-1900,10-1,1,10,0,0);
t. schedule(task,d);

2.  public void schedule(TimerTask task, Date firstTime, long period):在时间到达firstTime开始,每隔period毫秒就启动一次task指定的线程,这种方式会重复启动线程。
Date d = new Date(2009-1900,10-1,1,10,0,0);
t. schedule(task,d,20000);

3.  public void schedule(TimerTask task,long delay)在执行schedule方法delay毫秒以后启动线程task。
t.schedule(task,1000);//在执行该行启动代码1000毫秒后启动一次线程task

4.  public void schedule(TimerTask task,long delay,long period):在执行schedule方法delay毫秒以后启动线程task,然后每隔period毫秒重复启动线程task。

用定时器实现数字时钟功能:

package com.hbsi.thread;

 

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

 

/*

 * TestTime.java

 *

 * Created on __DATE__, __TIME__

 */

 

/**

 *

 * @author  __USER__

 */

public class rff extends javax.swing.JFrame {

 

    /**

     *

     */

    private static final long serialVersionUID = 1L;

 

    /** Creates new form TestTime */

    public rff() {

       initComponents();

    }

 

    /** This method is called from within the constructor to

     * initialize the form.

     * WARNING: Do NOT modify this code. The content of this method is

     * always regenerated by the Form Editor.

     */

    //GEN-BEGIN:initComponents

    // <editor-fold defaultstate="collapsed" desc="Generated Code">

    private void initComponents() {

 

       time = new javax.swing.JLabel();

 

       setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

 

       javax.swing.GroupLayout layout = new javax.swing.GroupLayout(

              getContentPane());

       getContentPane().setLayout(layout);

       layout.setHorizontalGroup(layout.createParallelGroup(

              javax.swing.GroupLayout.Alignment.LEADING).addGroup(

              layout.createSequentialGroup().addGap(20, 20, 20).addComponent(

                     time, javax.swing.GroupLayout.DEFAULT_SIZE, 407,

                     Short.MAX_VALUE).addContainerGap()));

       layout.setVerticalGroup(layout.createParallelGroup(

              javax.swing.GroupLayout.Alignment.LEADING).addGroup(

              layout.createSequentialGroup().addContainerGap().addComponent(

                     time, javax.swing.GroupLayout.DEFAULT_SIZE, 85,

                     Short.MAX_VALUE).addContainerGap()));

 

       pack();

    }// </editor-fold>

    //GEN-END:initComponents

 

    /**

     * @param args the command line arguments

     */

    public static void main(String args[]) {

       rff tt=new rff();

       tt.setVisible(true);

       // 创建Timer

       Timer t = new Timer();

       // 创建TimerTask

       TimerTask1 tt1 = new TimerTask1();

       // 启动线程

       t.schedule(tt1, 0);

              try {

                  while(true) {

                     Thread.sleep(1000);

                     Date d = new Date();

                      time.setText(d.toString());

                  }

              } catch (InterruptedException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }

}

    //GEN-BEGIN:variables

    // Variables declaration - do not modify

    private static javax.swing.JLabel time;

    // End of variables declaration//GEN-END:variables

}

class TimerTask1 extends TimerTask {

    public void run() {

       while (true) {

              try {

                  Thread.sleep(1000);

              } catch (InterruptedException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }

       }

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值