http://www.jianshu.com/p/c2eddba38bc2 http://blog.csdn.net/xiangyong_1521/article/details/78529102
当我们需要在几个线程中排个优先执行的顺序时,我们就需要用到线程优先的相关方法, Thread类有setPriority(int level)方法用来设置线程的优先级。 线程的有限级从1到10,1是最不重要的,10是最重要的。如果没有给线程设置优先级,那么线程的优先级将是默认值5.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Text1();
text2();
}
private void Text1() {
Thread thread1 = new Thread(new TestThead(1));
Thread thread2 = new Thread(new TestThead(2));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (Exception e) {
}
}
private void text2() {
}
class TestThead implements Runnable{
int id ;
public TestThead(int id ){
this.id=id;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
Log.i("md", "Thread" + id + ": " + i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
打印结果为:
Thread2: 1
Thread1: 1
Thread2: 2
Thread1: 2
Thread2: 3
Thread1: 3
Thread2: 4
Thread1: 4
Thread2: 5
Thread1: 5
Thread2: 6
Thread1: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
从这个例子可以看出当线程未设置优先级时,是交叉运行的!
当我们加了
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.setPriority(Thread.MIN_PRIORITY);
打印结果为:
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
Thread2: 1
Thread2: 2
Thread2: 3
Thread2: 4
Thread2: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有