一.可以使用setPriority方法来设置
线程测优先级 (有可能影响线程的执行顺序)
1- MIN_PRIORITY
10- MAX_PRIORITY
5- MAX_PRIORITY 默认
优先级高的可能先被使用
如结果所示,每次C都会先执行,但只是有可能影响
public class ThreadDemo04 {
public static void main(String[] args) {
MyThread1 d1 = new MyThread1();
MyThread1 d2 = new MyThread1();
MyThread1 d3 = new MyThread1();
Thread r1 = new Thread(d1,"A");
Thread r2 = new Thread(d2,"B");
Thread r3 = new Thread(d3,"C");
r1.setPriority(Thread.MIN_PRIORITY);
r2.setPriority(Thread.NORM_PRIORITY);
r3.setPriority(Thread.MAX_PRIORITY);
r1.start();
r2.start();
r3.start();
}
}
class MyThread1 implements Runnable{
@Override
public void run() {
for(int i=0;i<5;i++){
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" "+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
C 0
A 0
B 0
C 1
B 1
A 1
C 2
B 2
A 2
C 3
B 3
A 3
C 4
B 4
A 4
二.线程的同步问题
解决资源共享的问题
public class ThreadDemo05 {
public static void main(String[] args) {
MyThreadDemo d1 = new MyThreadDemo();
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d1);
Thread t3 = new Thread(d1);
t1.start();
t2.start();
t3.start();
}
}
class MyThreadDemo implements Runnable{
private int ticket = 5;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
// synchronized (this) {
// if(ticket>0){
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// System.out.println("车票"+ticket--);
// }
// }
tell();
}
}
public synchronized void tell() {
if(ticket>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("车票"+ticket--);
}
}
}