假设t是一个线程对象
//设置线程名字
t.setName("");
//获取线程名字
t.getName();
//启动线程,start()会瞬间执行完成,线程启动后会自动调用run()方法。
t.start();
//返回当前正在执行的线程对象,
Thread.currentThread()
//sleep()方法:使线程进入休眠,放弃占有cpu,这个方法出现在那个线程中,那个线程就休眠,可以间隔特定的时间执行特定的代码。(注意run()方法中的sleep()异常不能抛出,因为父类没有抛,子类不能抛出比父类更多的异常)
Thread.sleep();
//中断睡眠,执行这个方法的话,sleep()那里就会执行异常,然后try...catch...语句就结束了
t.interrupt()
//强行终止线程,在线程中设置一个run参数,在别的线程里改变这个参数以终止其运行
public class test {
public static void main(String[] args) {
MyThread r=new MyThread();
Thread t=new Thread(r);
t.setName("t");
t.start();
try {
t.sleep(1000*5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
r.run=false;
}
}
class MyThread implements Runnable{
boolean run=true;
public void run() {
if (run) {
for (int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}else {
return;
}
}
}