-->
当前位置:首页 > 题库 > 正文内容

单选题:多线程练习

Luz3年前 (2022-10-31)题库316
将以下两段代码在IDE中运行,查看相应结果并进行分析。
java
public class SellTicket extends Thread {
public static int iCount = 100;

public void run() {
while (true) {
{
if (iCount <= 0)
break;
System.out.println(Thread.currentThread().getName() + " sell " + iCount);
iCount--;
}
}
}

public static void main(String[] args) {
SellTicket st1 = new SellTicket();
SellTicket st2 = new SellTicket();
SellTicket st3 = new SellTicket();
SellTicket st4 = new SellTicket();

new Thread(st1).start();
new Thread(st1).start();
new Thread(st1).start();
new Thread(st1).start();

}
}


java
public class SellTicket2 extends Thread {
private static byte[] lock = new byte[0];
public SellTicket2(byte[] lock) {
//这里设置了锁定标志
this.lock = lock;
}
public static int iCount = 100;
public void run() {
while (true) {
// 这里使用了同步处理
synchronized (lock) {
if (iCount<=0) break;
System.out.println(Thread.currentThread().getName() + " sell " + iCount);
iCount--;
}
}
}

public static void main(String[] args) {
byte[] lock = new byte[0];
new Thread(new SellTicket2(lock)).start();
new Thread(new SellTicket2(lock)).start();
new Thread(new SellTicket2(lock)).start();
new Thread(new SellTicket2(lock)).start();
}
}







A.已掌握


答案:A

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。