关于java多线程的例子,恳请高手指点一下,谢谢!

来源:百度知道 编辑:UC知道 时间:2024/05/17 17:36:11
程序中建立mt1线程,还有mt2线程,我想让mt1建立之后进入休眠状态,而先执行mt2,可是还是先执行的mt1,这个是怎么回事?
public class MyThread extends Thread {
int num;

char c;

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

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

public void run() {

System.out.println("num=" + num + " c=" + c);

}

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

MyThread mt2 = new MyThread(4066, 'e');

mt2.start();

}

}

您的程序有点问题!
我帮您改正了,已经测试通过!仅供您参考!

public class MyThread extends Thread {
int num;

char c;

MyThread()
{
num = 1000;
c = 'd';

}

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

}

public void run() {
try {

Thread.sleep(7000);

}
catch (Exception e)
{
System.out.println("错误!");
}

System.out.println("num=" + num + " c=" + c);

}

public static void main(String[] args)
{
MyThread mt2 = new MyThread(4066, 'e');
mt2.start();
MyThread mt1 = new MyThread();
mt1.start();

}

}

MyThread mt1 = new MyThread();
这句话就已经建立了mt1线程,而mt1.start是把线程mt1起来了

要达到目的,可以这样m2.start();《——起m2线程
m2.join();《-主线程等待m2执行完
m1.start();《-起m1线程