java关于多线程的sleep初级问题

来源:百度知道 编辑:UC知道 时间:2024/06/14 01:31:04
两种创建线程的方法,具体如下
public class MainRunT
{
public static void main(String[] args)
{
MyThread mt= new MyThread();
mt.start();
for(int a=0;a<3;a++)
{
System.out.println("t"+a);
}
}
}

class MyThread extends Thread
{
int i;
public void run()
{
while(true)
{
System.out.println("aaa"+i++);
this.sleep(1000);
if(i==5)
break;
}
}
}
第二种
public class MainRun
{
public static void main(String[] args)
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
for(int a=0;a<3;a++)
{
System.out.println("Tt"+a);
}
}
}

class MyThread implements Runnable
{
int i;
public void run()
{
while(true)
{
System.out.println("Aa"+i

Thread.currentThread().sleep(1000);?

sleep()方法是静态(类)方法,不是实例方法,应该是Thread.sleep(1000);sleep()方法会抛出InterruptedException异常,你不处理,当然会报错

如果是先运行完main中的内容,再调用run()中的内容,那就不是多线程了,而是遇到start()就调用run()的内容,也就是说是多个线程并发(交替)运行

线程,当使用start()开启线程后,主main继续向下执行,同时线程一起运行。(main主线程和开启的线程并行)
sleep()方法要抛出InterruptedException,比必须处理,可以在main方法头后面加 throws Exception把异常抛到控制台或者try catch处理异常

要放在try catch语句结构中