public class Java多线程 {
public static void main(String[] args) throws InterruptedException {
Mythread1 th1=new Mythread1();
th1.start();
System.out.println("线程1是否是活的:"+th1.isAlive());
th1.join();//等待th1执行完再执行后边的,可设置需要等待的毫秒数
System.out.println("线程1是否是活的:"+th1.isAlive());
MyRunnbale runnable=new MyRunnbale();
Thread th2=new Thread(runnable);
th2.start();
System.out.println("ID:"+th2.getId()+" Name:"+th2.getName());//打印线程的ID和默认名字
th2.setName("Thread2");//设置线程的名字
System.out.println(th2.getName());//打印线程的名字
}
}
class Mythread1 extends Thread {//继承Thread类建立线程
public void run(){
System.out.println("线程1运行");
try {
mySleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void mySleep() throws InterruptedException{
for(int i=1;i<4;i++){
sleep(1000);
System.out.println("线程1休眠 "+i+" ms");
}
}
}
class MyRunnbale implements Runnable{//实现Runnable接口建立线程,是真正的可实现多线程(一般用这个)
public void run() {
System.out.println("线程2运行");
}
}
输出: