线程的常用方法

-------------siwuxie095

   

   

   

   

   

   

线程的常用方法基本都在 Thread 类中,Runnable 接口中只有一个 run() 抽象方法

   

1)取得线程名称:getName()

   

(2)取得当前线程对象:currentThread()

   

(3)判断线程是否启动:isAlive()

   

(4)线程的强行运行:join()

   

(5)线程的休眠:sleep()

   

(6)线程的礼让:yield()

   

   

   

   

   

代码:

   

package com.siwuxie095.thread;

   

   

class MyRunnableX implements Runnable{

 

private String name;

 

//构造方法,传入参数 name,用于标识当前线程

public MyRunnableX(String name) {

this.name=name;

}

 

 

//复写 Runnable run()方法

public void run() {

//(1)打印当前线程名称

//System.out.println("当前线程名称:"+Thread.currentThread().getName());

 

for (int i = 0; i < 10; i++) {

// (2)线程休眠

// try {

// //设置休眠时间为1秒,即 1秒执行一次

// //在打印 name-i 时,1秒打印一次,从视觉上看起来比较明显

// Thread.sleep(1000);

// } catch (InterruptedException e) {

// e.printStackTrace();

// }

 

System.out.println(name+"-"+i);

 

//(3)线程礼让

if (i==5) {

//当线程执行到5时进行礼让,另一个线程开始执行

System.out.println("礼让:");

Thread.yield();

}

}

}

}

   

   

public class ThreadDemoX {

   

public static void main(String[] args) {

MyRunnableX r1=new MyRunnableX("A");

MyRunnableX r2=new MyRunnableX("B");

//Runnable创建的线程依赖于Thread启动

Thread t1=new Thread(r1);

Thread t2=new Thread(r2);

//判断线程t1是否启动

System.out.println("t1启动:"+t1.isAlive());

t1.start();

t2.start();

System.out.println("t1启动:"+t1.isAlive());

System.out.println("当前线程名称:"+Thread.currentThread().getName());

System.out.println();

 

//(4)线程强行执行

//当主线程执行到10时,t1t2开始执行(强行),t1t2执行完毕,

//之后再把CPU资源让给主线程继续执行

// for (int i = 0; i < 20; i++) {

// if (i>10) {

//

// try {

// //如果i>10,强行执行t1t2线程

// //需要加 try catch 捕获异常

// t1.join();

// t2.join();

// } catch (InterruptedException e) {

// e.printStackTrace();

// }

// }

// System.out.println("主线程:"+i);

// }

 

}

   

}

   

   

运行一览:

   

线程是否启动 当前线程名称:

   

   

   

   

线程的强行运行:

   

 

   

   

 

线程的礼让:

   

   

   

   

   

   

   

【made by siwuxie095】

 

原文地址:https://www.cnblogs.com/siwuxie095/p/6629106.html