关于线程
class MyThread extends Thread {private int ticket = 5;
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
/* for(int i = 0;i < 10; i++)
System.out.println(name + "运行, i = " + i); */
for(int i = 0;i<10;i++){
if(ticket > 0)
System.out.println(name + "卖票:ticket = " + ticket--);
}
}
}
public class ThreadDemo01 {
public static void main (String args[]) {
MyThread mt1 = new MyThread("线程A");
MyThread mt2 = new MyThread("线程B");
MyThread mt3 = new MyThread("线程C");
mt1.start();
mt2.start();
mt3.start();
}
}
运行结果:
线程A卖票:ticket = 5
线程A卖票:ticket = 4
线程A卖票:ticket = 3
线程A卖票:ticket = 2
线程A卖票:ticket = 1
线程B卖票:ticket = 5
线程B卖票:ticket = 4
线程B卖票:ticket = 3
线程B卖票:ticket = 2
线程B卖票:ticket = 1
线程C卖票:ticket = 5
线程C卖票:ticket = 4
线程C卖票:ticket = 3
线程C卖票:ticket = 2
线程C卖票:ticket = 1
为什么3个线程不是交错运行的