一、获取当前运行的线程
package practice;
//获取当前运行的线程
public class Chapter9 {
public static void main(String args[]) {
String name;
int p;
Thread curr;
curr=Thread.currentThread();
System.out.println(curr);
p=curr.getPriority();
name=curr.getName();
System.out.println(p+ " "+name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
二、通过继承实现多线程
package practice;
//通过继承实现多线程
class UserThread extends Thread{ //定义多线程类
int sleepTime=0;
public UserThread(String id){ //构造函数
super(id);
sleepTime=(int)(Math.random()*1000); //随机产生睡眠时间,睡眠0~1000毫秒
System.out.println("线程名:"+getName()+",睡眠: "+sleepTime+"ms");
}
public void run() { //覆盖父类方法
try {
Thread.sleep(sleepTime); //可能产生中断异常
}catch(InterruptedException e) {
System.out.println("运行异常!"+e.toString());
}
System.out.println("当前运行的线程是:"+getName());
}
}
public class Chapter9 {
public static void main(String args[]) {
UserThread t1,t2,t3,t4; //定义4个线程引用
t1=new UserThread("No 1");
t2=new UserThread("No 2");
t3=new UserThread("No 3");
t4=new UserThread("No 4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
三、通过实现Runnable接口创建多线程
package practice;
//通过实现Runnable接口创建多线程
class UserThread implements Runnable { //实现接口,定义多线程类
int num;
UserThread(int n){num=n;} //构造函数
public void run() { //run方法的实现
for(int i=0;i<3;++i)
System.out.println("运行线程:"+num);
System.out.println("结束:"+num);
}
}
public class Chapter9 {
public static void main(String args[]) {
Thread mt1=new Thread(new UserThread(1));
Thread mt2=new Thread(new UserThread(2));
mt1.start();
mt2.start();
try {
mt1.join(); //等待线程死亡
mt2.join();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}