priority -- join -- yield

本文通过三个示例程序深入探讨了Java中线程的创建、调度及优先级设定等内容,包括使用yield方法让出CPU执行权、使用join方法等待线程结束以及设置线程优先级等关键操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class TestYild {
  public static void main(String[] args) {
    MyThread3 t1 = new MyThread3("t1");
    MyThread3 t2 = new MyThread3("t2");
    t1.start(); t2.start();
  }
}
class MyThread3 extends Thread {
  MyThread3(String s){super(s);}
  public void run(){
    for(int i =1;i<=100;i++){
      System.out.println(getName()+": "+i);
      if(i%10==0){
        yield();<span style="white-space:pre">			</span>//作用是让出CPU一次
      }
    }
  }
}
public class TestJoin {
	public static void main(String[] args) {
		MyThread4 ss = new MyThread4("ss");
		ss.start();
		try{
			ss.join();<span style="white-space:pre">			</span>//join是将当前线程合并,在这里是将ss线程合并到main函数中
		} catch(InterruptedException e) {}
		
		for(int i=0;i<10;i++){
			System.out.println("main:" + i);
			
			try {
				Thread.sleep(1000);
			}	catch(InterruptedException e) {}
		
		}
	}
}

class MyThread4 extends Thread{
	MyThread4(String s) {
		super(s);
	}
	public void run(){
		for(int i=0;i<10;i++){
			System.out.println(getName() + i);
			try{
				sleep(1000);
			}	catch(InterruptedException e) {
				return;
			}
		}
	}
}
public class TestPriority {
	public static void main(String[] args) {
	Thread t1 = new Thread(new T1());
	Thread t2 = new Thread(new T2());
	t1.setPriority(Thread.NORM_PRIORITY +3);<span style="white-space:pre">		</span>//这里是指设置优先级,<span style="font-family: Arial, Helvetica, sans-serif;">NORM_PRIORITY这是默认的优先级,是5</span>

	t1.start();
	t2.start();
	}	
}

class T1 implements Runnable {
	public void run() {
		for(int i=0;i<100;i++) {
			System.out.println("T1:" + i);	
		}	
	}	
}

class T2 implements Runnable {
	public void run() {
		for(int i=0;i<100;i++) {
			System.out.println("    T2:" + i);	
		}	
	}	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值