线程停止 06

线程停止

  • setPriority(int newPriority) (更改线程的优先级)

  • static void sleep(long millis) (在指定的毫秒内让当前正在执行的线程体休眠)

  • void join() (等待线程终止)

  • static void yield() (暂停当前正在执行的线程对象,并执行其它线程)

  • void interrupt() (中断线程,不用这个方法)

  • Boolean isAlive() (测试线程是否处于活动状态)

package Runnable1;
/*
1.建议线程正常停止-->利用次数,不建议死循环
2.建议使用标准志位-->设置一个标志位
3.不要使用stop或者destroy等过时或者jdk不建议使用的方法
*/
public class TestStop implements Runnable
{
   private boolean flag=true;
   public static void main(String[] args)
  {
       TestStop testStop=new TestStop();
       new Thread(testStop,"").start();
       for (int i = 0; i < 100; i++)
      {
           System.out.println("main"+i);
           if (i==900)
               //调用stop方法
               testStop.stop();
           System.out.println("线程该停止了");
      }
  }

   @Override
   public void run()
  {
       if (flag) {
           for (int i = 0; i < 100; i++) {
               System.out.println("run...Thread"+i++);
          }

      }
  }
   //设置一个公开的方法停止线程,转换标记志位
   public void stop()
  {
       this.flag=false;
  }
}

 

  • 线程的停止:使用stop()方法停止一个线程,会使线程发生死锁,不推荐使用。

  • 其它方法:1. 把当前线程对象设置为空。

                             2. 为线程设置一个布尔标志,定期的检测,标记是否为真。如要停止一个线程,就把标记为true。

package src;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;


public class Clock extends JFrame
{
JPanel p=new JPanel();
JLabel lab=new JLabel();
JButton btn1=new JButton("开始");
JButton btn2=new JButton("暂停");
Date nowtime;
Thread t;
boolean flag;
public Clock()
{
p.add(lab);
p.add(btn1);
p.add(btn2);
btn1.addActionListener(new time());
btn2.addActionListener(new time());
this.setContentPane(p);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(300,100);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
public void gettime()
{
nowtime =new Date();
SimpleDateFormat f=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒SSS毫秒   EEE");//SimpleDateFormat是一个格式化和解析日期的类
String str=f.format(nowtime.getTime());//获取当前时间并以指定的格式f转化为字符串
lab.setText(str);
}
public static void main(String[] args)
{
Clock fr=new Clock();
fr.gettime();
fr.setVisible(true);
}
class time implements ActionListener
{
public void actionPerformed(ActionEvent e)
{

   if (e.getSource()==btn1)
  {
  flag=true;
  t=new Thread(new thread());
  t.start();
  }
else if (e.getSource()==btn2)
{
flag=false;
}
}
}
class thread implements Runnable
{

@Override
public void run()
{
while (flag)
{
gettime();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}


}
}
}
 
posted @   zjw_rp  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示