我们先来介绍两个方法:
currentThread():返回对当前正在执行的线程对象的引用。
getName():返回该线程的名称。
其实每个线程系统都会给其设定名字的,下面我们来创建三个线程,使用currentThread().getName()来获取系统给他们设定的名字:
public class GetNameForThread {
@Test
public void t(){
new getname().start();
new getname().start();
new getname().start();
}
}
class getname extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("当前线程的名字是:" + currentThread().getName());
//System.out.println("当前线程的名字是:" + this.getName());
}
}
有没有发现输出的结果很奇怪,并没有按照顺序来输出,而且每次输出的顺序还不一样,其实是因为在输出的时候它们在争抢资源。并不是说我们按照顺序启动就会按照顺序输出,我们启动了之后,它们只是在就绪状态,当CPU调度它们的时候,它们才进入run方法执行。
现在提出一个问题,系统能给线程设定名字,那能不能认为设定名字呢?当然是能的,下面我们来自己设定一下线程的名字:
public class SetNameForThread {
@Test
public void t(){
name name = new name("线程名1");
name.start();
}
}
class name extends Thread{
private String threadName;
public name() {
}
public name(String threadName) {
this.threadName = threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("此线程的名字是:" + this.threadName);
}
}
我们在上一篇中知道了怎么启动线程,那怎么停止它呢?会不会有个stop方法呢?嗯,的确有,但是我们查看API可以发现,使用stop方法来停止线程已经过时了,那使用什么方法呢?下面我们来介绍三个方法。
sleep(long millis):让线程在指定的毫秒数内休眠(我们需要知道的是,休眠并不是停止线程,而是让其进入就绪状态,就绪状态的线程不是中断的)
interrupt():中断线程
isInterrupted():测试线程是否已经中断
public class StopThreadByInterrupt {
public static void main(String[] args) {
interruptA ia = new interruptA();
ia.start();
try {
//让线程在3秒内休眠
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ia.interrupt();
}
}
class interruptA extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
while(!isInterrupted()){
System.out.println("我是线程" + currentThread().getName());
}
}
}
上面我们使用了Java提供的方法来中断线程,接下来给介绍一个通过boolean来中断的方法。
public class StopThreadOfBoolean {
public static void main(String[] args) throws Exception {
stopAByBool sabb = new stopAByBool();
sabb.start();
Thread.sleep(3000);
sabb.setBool(false);
}
}
class stopAByBool extends Thread{
private boolean bool = true;
public void setBool(Boolean bool){
this.bool = bool;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(bool){
System.out.println("线程:" + this.getName());
}
}
}