线程停止 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("线程该停止了");
}
}
-
线程的停止:使用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();