Thread 方法
下表列出了Thread类的一些重要方法:
序号 方法描述
1 public void start()
使该线程开始执行;Java 虚拟机调用该线程的 run 方法。
2 public void run()
如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。
3 public final void setName(String name)
改变线程名称,使之与参数 name 相同。
4 public final void setPriority(int priority)
更改线程的优先级。
5 public final void setDaemon(boolean on)
将该线程标记为守护线程或用户线程。
6 public final void join(long millisec)
等待该线程终止的时间最长为 millis 毫秒。
7 public void interrupt()
中断线程。
8 public final boolean isAlive()
测试线程是否处于活动状态。
用户线程:无论主线线程是否结束,用户线程都会跑完。非用户线程在主线程跑完后会自动终止
通过实现接口方式,实现多线程
/**
* 通过实现接口方式,实现多线程
* @author Administrator
*
*/
public class ThreadConuer{
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread(new PrintString("hello",1000));
t.setDaemon(true); //用户线程
t.setName("hello"); //修改线程名字
t.start();
}
}
/**
* 打印字符串n次
* @author Administrator
*
*/
class PrintString implements Runnable {
String str = null;
int n;
public PrintString (String s,int n){
str = s;
this.n = n;
}
@Override
public void run() {
for(int i=0;i<n;i++)
System.out.println(str);
}
}
通过继承方法。实现多线程
/**
* 通过继承方法。实现多线程
* @author Administrator
*
*/
public class ThreadInherit{
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new PrintString2("Hello",1000);
t.setDaemon(true); //用户线程
t.setName("hello"); //修改线程名字
t.start();
}
}
/**
* 打印字符串n次
* @author Administrator
*
*/
class PrintString2 extends Thread{
String str = null;
int n;
public PrintString2 (String s,int n){
str = s;
this.n = n;
}
@Override
public void run(){
for(int i=0;i<n;i++)
System.out.println(str);
}
}