JAVA学习笔记--多线程(二)线程常用方法

Thread类包含的方法
start()     启动线程
isAlive()   判断线程当前是否正在运行
setPriority()  设置优先级
jion()         使一个线程等待另一个线程结束
sleep(mills:long)  指定线程休眠指定毫秒

yield()    使线程暂停并允许执行其他进程

wait() 和notify() 等待与唤醒

interrupt()  中断线程(极少使用)


yield():


public class PrintChar implements Runnable {
	char ch;
	int count=0;
	public PrintChar(char ch,int count){
	    this.ch=ch;
	    this.count=count;
		}
	public void run() {
		for(int i=0;i<count;i++){
			System.out.print(" "+ch);
			Thread.yield();
		}
	}
}


sleep(mills:long):
sleep()方法可能抛出一个InterruptedException,这是一个必检异常,因此sleep()
方法必须放在try-catch语句块内


public class PrintNum implements Runnable{
	int num;
	int count;
 public PrintNum (int Num,int count){
	 this.num=Num;
	 this.count=count;
 }
 @Override
public void run() {
	// TODO Auto-generated method stub
 for(int i=0;i<count;i++){
	 System.out.print(num);
	 if(i>20){
		 try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }
     }	
   }
}

jion()         使一个线程等待另一个线程结束


public class PrintChar implements Runnable {
	char ch;
	int count=0;
	Thread print_num =new Thread(new PrintNum('b', 20));
	public PrintChar(char ch,int count){
	    this.ch=ch;
	    this.count=count;
		}
	public void run() {
		for(int i=0;i<count;i++){
			System.out.print(" "+ch);
			if (i==30) {
				try {
					print_num.join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

setPriority(),在主程序中调用,用以设置优先级,Thread类下定义了三个int型的优先级
MIN_PRIORITY=1,MAX_PRIORITY=10,NORM_PRIORITY=5


public class Print {
   public static void main(String[] args) {
		Runnable pc=new PrintChar('A', 100);
		Runnable pn=new PrintNum(9, 100);
		
	    Thread th1=new Thread(pc);
	    Thread th2=new Thread(pn);
	    
	    th1.setPriority(Thread.MIN_PRIORITY);
	    
	    th1.start();
	    th2.start();
     }
}


wait() 和notify()与Synchronized关键字在下一节一起学习

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值