1.start():启动当前线程并调用线程的run()方法
2.run():将创建线程要执行的操作声明在此
3.currentThread():静态方法,放回当前代码执行的线程
4.getName():获取当前线程的名字
5.setName():设置当前线程的名字
6.yield():释放当前cpu的执行权
7.join():在线程A中调用线程B的join方法,使得线程A进入阻塞状态,直到线程B完全执行完,线程A才结束阻塞状态
8.stop():已过时,在执行此方法时,强制结束该线程
9.sleep(long long millis):让当前线程睡眠指定的millis毫秒时间内(睡眠即当前线程为阻塞状态)
10.isAlive():判断当前线程是否还存活
代码示例:
1 class HelloThread extends Thread { 2 public void run() { 3 for (int i = 0; i <= 100; i += 2) { 4 System.out.println(Thread.currentThread().getName() + ":" + i); 5 if (i % 20 == 0) { 6 try { 7 sleep(1000); 8 } catch (InterruptedException e) { 9 throw new RuntimeException(e); 10 } 11 this.yield(); 12 } 13 } 14 } 15 16 public HelloThread() { 17 super(); 18 } 19 20 public HelloThread(String name) { 21 super(name); 22 } 23 } 24 25 public class ThreadMethodTest { 26 public static void main(String[] args) { 27 //命名方法1 28 HelloThread h1 = new HelloThread(); 29 h1.setName("线程1"); 30 h1.start(); 31 //命名方法2 32 HelloThread h2 = new HelloThread("线程2"); 33 h2.start(); 34 //给主线程命名 35 Thread.currentThread().setName("主线程"); 36 for (int i = 1; i < 100; i += 2) { 37 System.out.println(Thread.currentThread().getName() + ":" + i); 38 if (i == 21) { 39 try { 40 h1.join(); 41 } catch (InterruptedException e) { 42 throw new RuntimeException(e); 43 } 44 } 45 } 46 System.out.println(Thread.currentThread().getName()); 47 System.out.println(h1.isAlive()); 48 } 49 50 }
二.线程的优先级:
1.
MAX_PRIORITY:10
MIN_PRIORITY:1
NORM_PRIORITY:5
2.设置和获取优先级
getPriority():获取线程的优先级
setPriority(int p):设置线程的优先级
3.高优先级意味着有更高的概率被执行,并不意味着一定是高优先级的线程全部执行完后才执行低优先级的
1 //设置线程的优先级 2 h1.setPriority(10); 3 Thread.currentThread().setPriority(Thread.NORM_PRIORITY);