java多线程总结(二)之Thread类的常用方法

1.Thread类的常用方法

(1)sleep()

      导致当前正在执行的县城休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性。

package com.thread;

class MyRunnable implements Runnable{
	@Override
	public void run() {
		
    for (int i = 1; i < 10; i++) {
		System.out.println(i);
		
		 try {
			Thread.sleep(2000);//线程休眠2秒
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		 
	}
   }
}
public class Demo01{
	public static void main(String[] args)  {
		 MyRunnable myRunable=new MyRunnable();
		 Thread thread1=new Thread(myRunable);
		 thread1.start();
	} 
}		

输出结果:间隔两秒输出下一个值。

(2)yield()

线程让步是通过Thread.yield()实现,让当前进程停下换成就绪状态,让系统的调度器重新调度,但yield()方法不会阻塞当前线程,它与其他线程是相对公平的,等待线程再一次调度,有可能调度的是其他线程也可能还调度的是自己。

package com.thread;

class MyRunnable implements Runnable{
	@Override
	public void run() {
		
    for (int i = 1; i <100; i++) {
		System.out.println(Thread.currentThread().getName()+i);
		Thread.yield();//线程让步
	}
   }
}
public class Demo01{
	public static void main(String[] args)  {
		 MyRunnable myRunable=new MyRunnable();
		 Thread thread1=new Thread(myRunable);
		 thread1.start();
		 for (int i = 1; i < 100; i++) {
				System.out.println(Thread.currentThread().getName()+i);
		}
	} 
}		

输出结果:

由结果可看出,线程让步之后还可能调度自己。

(3)join()

线程插队,阻塞当前线程,让调用了join的这个方法的这个线程先执行,等这个线程执行完毕,才来执行其他线程。

package com.thread;

class MyRunnable implements Runnable{
	@Override
	public void run() {
    for (int i = 1; i <10; i++) {
		System.out.println(Thread.currentThread().getName()+i);
	}
   }
}
public class Demo01{
	public static void main(String[] args) throws InterruptedException  {
		 MyRunnable myRunable=new MyRunnable();
		 Thread thread1=new Thread(myRunable);
		 thread1.start();
		 for (int i = 1; i < 10; i++) {
				System.out.println(Thread.currentThread().getName()+i);
				if(i==5) {
					thread1.join();
				}
		}
	} 
}		

(4)interrupted()

 中断此线程,默认为false。

package com.thread;

import java.io.IOException;

class MyRunnable implements Runnable{
	@Override
	public void run() {
		while(!Thread.interrupted()){
			System.out.println(Thread.currentThread().getName()+"线程执行中");
		}
   }
}
public class Demo01{
	public static void main(String[] args) throws InterruptedException, IOException  {
		 MyRunnable myRunable=new MyRunnable();
		 Thread thread1=new Thread(myRunable);
		 
		 thread1.start();
		 System.in.read();//键盘录入一个值
		 thread1.interrupt();//打断当前线程
	} 
}		

输出结果,键盘录入值之前一直打印,当录入值之后线程被打断,不再输出值,线程终止。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值