java中多线程,哪里错了呢?

来源:百度知道 编辑:UC知道 时间:2024/07/04 12:28:45
先建立了一个线程,启动后就休眠一段时间,再建立一个线程没有休眠,可是还是先执行第一个线程,这是怎么回事?
public class MyThread extends Thread {
int num;
char c;

MyThread() {
num = 4055;
c = 'd';
}

MyThread(int a, char b) {
num = a;
c = b;
}

public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("num=" + num + " c=" + c);
}
}

public static void main(String[] args) {
MyThread mt1 = new MyThread();
try {
mt1.sleep(7000);
} catch (Exception e) {
System.out.println("错误!");
}
mt1.start();
MyThread mt2 = new MyThread(4066, 'e');
mt2.start();
}
}

这是我改过的程序,加了一些输出:
public class MyThread extends Thread {
int num;
char c;

MyThread() {
num = 4055;
c = 'd';
}

MyThread(int a, char b) {
num = a;
c = b;
}

public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("num=" + num + " c=" + c);
}
}

public static void main(String[] args) {

MyThread mt1 = new MyThread();
try {
System.err.println("A");
mt1.sleep(900);
System.err.println("B");
} catch (Exception e) {
System.err.println("错误!");
}
System.err.println("C");
mt1.start();
System.err.println("D");
MyThread mt2 = new MyThread(4066, 'e');
mt2.start();
}
}

这是其中一次的运行结果:
A
B
C
D
num=4055 c=d
num=4055 c=d