多线程4-线程状态与常用方法

时间:2021-07-29 18:37:22

线程的状态

1.线程也有固定的操作状态

  1. 创建状态:准备好了一个多线程的对象
  2. 就绪状态:调用了start()方法,等待CPU进行调度
  3. 运行状态:执行run()方法
  4. 阻塞状态:暂时停止执行,可能将资源交给其他线程使用
  5. 终止状态:(死亡状态)线程销毁
    (阻塞可以恢复为运行状态)

线程的常用方法

1.取得线程名称
getName()

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

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

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

5.线程的休眠
sleep()

6.线程的礼让
yield()

//先获得线程对象才能获得线程名称
public class RunDemo implements Runnable{
private String name;
public RunDemo(String name){
this.name=name;
}

public void run(){
for(int i=0;i<50;i++){
System.out.println("当前线程对象:"+Thread.currentThread().getName());
}
}
}

public class DemoTest{
public static void main(String[] args){
RunDemo r1=new RunDemo("A");
RunDemo r2=new RunDemo("B");
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
r1.start();
r2.start();
}
}
//当前线程是否在启动
public class RunDemo implements Runnable{
private String name;
public RunDemo(String name){
this.name=name;
}

public void run(){
for(int i=0;i<50;i++){
System.out.println(name+":"+i);
}
}
}

public class DemoTest{
public static void main(String[] args){
RunDemo r1=new RunDemo("A");
Thread t1=new Thread(r1);
System.out.println(t1.isAlive());
t1.start();
System.out.println(t1.isAlive());
}
}
//线程强行运行
public class RunDemo implements Runnable{
private String name;
public RunDemo(String name){
this.name=name;
}

public void run(){
for(int i=0;i<50;i++){
System.out.println(name+":"+i);
}
}
}

public class DemoTest{
public static void main(String[] args){
RunDemo r=new RunDemo("A");
Thread t=new Thread(r);
t.start();
for(int i=0;i<50;i++){
if(i>10){
try{
t.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println("主线程:"+i);
}
}
}
//线程的沉睡
public class RunDemo implements Runnable{
private String name;
public RunDemo(String name){
this.name=name;
}

public void run(){
for(int i=0;i<50;i++){
try{
Thread.sleep(1000);
System.out.println(name+":"+i);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
//线程的礼让
public class RunDemo implements Runnable{
private String name;
public RunDemo(String name){
this.name=name;
}

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 DemoTest{
public static void main(String[] args){
RunDemo r1=new RunDemo("A");
RunDemo r2=new RunDemo("B");
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
}