线程B运行7次 线程B运行8次 线程B运行9次 线程A运行2次 线程A运行3次 线程A运行4次 线程A运行5次 线程A运行6次 线程A运行7次 线程A运行8次 线程A运行9次
使用
Thread.currentThread().getName()方法,修改卖票程
序,显示出哪个线程在卖第几张票。三个线程的名字分别是”A”, ”B”, ”C”
class MyThread implements Runnable {
private int ticket=5; public void run() {
System.out.println(Thread.currentThread().getName()+\卖第for(int i=1;i<10;i++) {
if(ticket>0)
\张票\ }
public class Test {
public static void main(String args[]) { } }
}
}
MyThread th1=new MyThread(); Thread t1=new Thread(th1,\Thread t2=new Thread(th1,\Thread t3=new Thread(th1,\t1.start(); t2.start(); t3.start();
运行结果如下: A卖第5张票 C卖第3张票 C卖第2张票 B卖第4张票 A卖第1张票
在java的线程操作中,所有的线程在运行前都会保持在就绪状态,那么此时,哪个线程的优先级高,哪个线程就有可能会被先执行。 设置优先级:
void setPriority(int newPriority) setPriority(Thread.MIN_PRIORITY) ; // 优先级最低
setPriority(Thread.MAX_PRIORITY) ; // 优先级最高
setPriority(Thread.NORM_PRIORITY) ; // 优先级正常
class MyThread implements Runnable {
private int ticket=100;
public void run() {
System.out.println(Thread.currentThread().getName()+\卖第for(int i=1;i<1000;i++) {
if(ticket>0)
\张票\ }
public class Test {
public static void main(String args[]) {
MyThread th1=new MyThread(); Thread t1=new Thread(th1,\Thread t2=new Thread(th1,\Thread t3=new Thread(th1,\t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); t3.setPriority(Thread.NORM_PRIORITY); } }