一, 线程常用的方法
。。。
/* * Thread(String name) 初始化线程的名字 getName() 返回线程的名字 setName(String name) 设置线程对象名 sleep() 线程睡眠指定的毫秒数。 getPriority() 返回当前线程对象的优先级 默认线程的优先级是5 setPriority(int newPriority) 设置线程的优先级 虽然设置了线程的优先级,但是具体的实现取决于底层的操作系统的实现(最大的优先级是10 ,最小的1 , 默认是5)。 currentThread() 静态方法,哪个线程执行就返回这个线程的对象 返回CPU正在执行的线程的对象 * */ public class test_1 extends Thread { public test_1 (String name) { super(name); } @Override public void run() { // System.out.println("this: " + this); // System.out.println("当前对象: " + Thread.currentThread()); for(int i=0;i<5;i++) { System.out.println(this.getName()+ ": " + i); // 为什么在这里不能抛出异常,只能捕获?? 子类抛出异常必须小于或等于父类异常 /* try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } } public static void main(String args[]) throws Exception { // test_1 hh = new test_1(); // System.out.println("线程名称: " + hh.getName()); test_1 hhhh = new test_1("付祖贤"); // System.out.println("线程名称2: " + hhhh.getName()); // hhhh.sleep(1000); // 静态方法,是主线程在睡眠,因为这句代码是主线程执行 hhhh.setName(" 女侠 "); hhhh.setPriority(10); // 优先级的数字越大,优先级越高,优先级的范围为: 1~10 hhhh.start(); for(int i=0;i<5;i++) { System.out.println(Thread.currentThread().getPriority()+ ": " + i); } Thread mainthread = Thread.currentThread(); System.out.println("main: " + mainthread.getName()); // 线程的优先级默认为5 System.out.println("自定义的线程优先级: " + hhhh.getPriority()); System.out.println("主线程优先级: " + Thread.currentThread().getPriority()); } }