多线程2(3)

2019-03-23 15:08

线程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); } }


多线程2(3).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:南工大概率统计A卷B卷

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: