public class ThreadMethodDemo {
public static void main(String[] args) {
System.out.println("main 线程的id:" + Thread.currentThread().getId());
System.out.println("main 线程的名称:" + Thread.currentThread().getName());
MyThread3 myThread = new MyThread3();
Thread thread1 = new Thread(myThread);
// setName() 可以设置线程名称
thread1.setName("线程A");
// 也可以通过构造器设置线程名称
Thread thread2 = new Thread(myThread, "线程B");
// 设置线程的优先级 [1~10]
// 线程优化级较高的线程不一定先执行,线程的调度终还是取决于操作系统
thread1.setPriority(1);
thread2.setPriority(10);
System.out.println("thread1 是在否活动 :" + thread1.isAlive());
System.out.println("thread2 是在否活动 :" + thread2.isAlive());
thread1.start();
thread2.start();
// 不能重复调用start()
// thread2.start();
System.out.println("thread1 是在否活动 :" + thread1.isAlive());
System.out.println("thread2 是在否活动 :" + thread2.isAlive());
// 主线程sleep 5s
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// TODO Auto‐generated catch block
e.printStackTrace(); }
}
System.out.println("5 秒后....");
}
}
class MyThread3 implements Runnable {
@Override
public void run() {
// 实现Runnable接口的,无法直接使用getId(),getName()等方法
// 需要使用Thread.currentThread() 来获取到当前对象才行
System.out.println("线程的id:" + Thread.currentThread().getId());
System.out.println("线程的名称:" + Thread.currentThread().getName());
for (int i = 0; i < 100; i++) {
System.out.println("线程的id:" + Thread.currentThread().getId()
+ " 线程的名称:" + Thread.currentThread().getName()
+ " 线程优先级:" + Thread.currentThread().getPriority());
}
}
}