单选题:多线程练习
将以下两段代码在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
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