复制代码
- //代码实例
- public class YieldAndPriority {
- public static void main(String[] args) {
- Runnable task1 = new Runnable() {
- @Override
- public void run() {
- int count = 0;
- //yield,让线程进入就绪态,CPU可能会调度该线程,使得该线程变为执行状态
- Thread.yield();
- while (true) {
- System.out.println("-------> task1 count=" + count++);
- }
- }
- };
- Runnable task2 = new Runnable() {
- @Override
- public void run() {
- int count = 0;
- while (true) {
- System.out.println(" --------------------------------------> task2 count=" + count++);
- }
- }
- };
- Thread t1 = new Thread(task1, "t1");
- Thread t2 = new Thread(task2, "t2");
- //设置优先级1-10 越大优先级越高
- t1.setPriority(1);
- t2.setPriority(10);
- t1.start();
- t2.start();
- }
- }
复制代码
- //输出结果
- ...
- --------------------------------------> task2 count=34436
- --------------------------------------> task2 count=34437
- --------------------------------------> task2 count=34438
- --------------------------------------> task2 count=34439
- --------------------------------------> task2 count=34440
- --------------------------------------> task2 count=34441
- --------------------------------------> task2 count=34442
- --------------------------------------> task2 count=34443
- --------------------------------------> task2 count=34444
- -------> task1 count=42407
- -------> task1 count=42408
- -------> task1 count=42409
- -------> task1 count=42410
- -------> task1 count=42411
- -------> task1 count=42412
- -------> task1 count=42413
- -------> task1 count=42414
- -------> task1 count=42415
- -------> task1 count=42416
- 进程已结束,退出代码130
欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) | Powered by Discuz! X3.4 |