线程的常用方法
线程的常用方法基本都在Thread类中,所以大部分都是通过Thread类进行调用的
1.取得当前线程的名称:
getName()
2.取得当前线程对象:
currentThread()
3.判断线程是否启动:
isAlive()
4.线程的强行运行:
join()
5.线程的休眠
sleep()
6.线程的礼让(针对生命周期是非常重要的 )
yield()
=============================================================
ThreadDemo03.java
线程未启动之前是false,启动之后是true
当主线程执行到10的时候,自己的线程开始执行,执行完毕后将cpu资源让给主线程
package thread;
class RunnableDemo implements Runnable{
private String name;
//创建构造方法,以标识当前哪一个线程执行
public RunnableDemo(String name) {
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
//线程休眠1秒钟
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println("当前线程对象:"+Thread.currentThread().getName());
System.out.println(name+":"+i);
}
}
}
public class ThreadDemo03 {
public static void main(String[] args) {
//实例化线程对象
RunnableDemo r1=new RunnableDemo("A");
//RunnableDemo r2=new RunnableDemo("B");
Thread t1=new Thread(r1);
//判断线程是否启动,
//System.out.println(t1.isAlive());
//Thread t2=new Thread(r2);
t1.start();
//t2.start();
//启动之后再来判断
//System.out.println(t1.isAlive());
for (int i = 0; i < 50; i++) {
if(i>10) {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("主线程:"+i);
}
}
}
=========================================================
线程的礼让
package thread;
class RunnableDemo implements Runnable{
private String name;
//创建构造方法,以标识当前哪一个线程执行
public RunnableDemo(String name) {
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(name+":"+i);
if (i==10) {
System.out.println("礼让");
Thread.yield();
}
}
}
}
public class ThreadDemo03 {
public static void main(String[] args) {
//实例化线程对象
RunnableDemo r1=new RunnableDemo("A");
RunnableDemo r2=new RunnableDemo("B");
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
}