1.getName(); 返回该线程的名称。
2.currentThread();返回对当前正在执行的线程对象的引用。
3.isAlive();测试线程是否处于活动状态。
4.sleep();线程休眠。
5.setPriority(int newPriority);更改线程的优先级。
6.yield();暂停当前正在执行的线程对象,并执行其他线程。
实例如下:
测试getName(); 返回该线程的名称。
currentThread();返回对当前正在执行的线程对象的引用。
public class Demo1 implements Runnable{
public void run() {
for(int i=0;i<10;i++){
// 获取当前线程
Thread t=Thread.currentThread();
System.out.println(t.getName()+":"+i); // 返回线程的名称
}
}
//测试返回线程的名称
public static void main(String[] args) {
Demo1 demo1=new Demo1();
new Thread(demo1).start();
new Thread(demo1).start();
new Thread(demo1,"线程3").start();
}
}
测试isAlive();测试线程是否处于活动状态。
public class Demo2 implements Runnable{ public void run() { for(int i=0;i<10;i++){ // 获取当前线程 Thread t=Thread.currentThread(); System.out.println(t.getName()+":"+i); // 返回线程的名称 } } public static void main(String[] args) { Demo2 demo2=new Demo2(); Thread t1=new Thread(demo2); System.out.println("t1是否活动:"+t1.isAlive()); t1.start(); System.out.println("t1是否活动:"+t1.isAlive()); } }测试 setPriority(int newPriority);更改线程的优先级。
public class Demo4 implements Runnable{ public void run() { // TODO Auto-generated method stub for(int i=0;i<10;i++){ try { Thread.sleep(1000); // 获取当前线程 Thread t=Thread.currentThread(); System.out.println(t.getName()+":"+i); // 返回线程的名称 } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Demo4 demo4=new Demo4(); Thread t1=new Thread(demo4,"线程A"); Thread t2=new Thread(demo4,"线程B"); Thread t3=new Thread(demo4,"线程C"); t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); t3.setPriority(Thread.NORM_PRIORITY); t3.start(); t1.start(); t2.start(); } }测试 yield();暂停当前正在执行的线程对象,并执行其他线程。
public class Demo5 implements Runnable{ public void run() { // TODO Auto-generated method stub for(int i=0;i<10;i++){ try { Thread.sleep(100); // 获取当前线程 Thread t=Thread.currentThread(); System.out.println(t.getName()+":"+i); // 返回线程的名称 if(i==5){ System.out.println("线程礼让:"); Thread.currentThread().yield(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { Demo5 demo1=new Demo5(); new Thread(demo1,"线程A").start(); new Thread(demo1,"线程B").start(); } }