分别定义 “DownloadThread”子类和“MusicThread”子类,来实现多线程。使两个子类重写后的“run()”方法在控制台每隔一秒分别输出“下载” 及“听歌”即可,并观察两者每次的输出顺序。
求写法
自定义类继承extends Thread,重写run方法,方法内通过while(true)循环,并且通过sleep(1000)实现每隔1秒执行一次。
public class DownloadThread extends Thread{
@Override
public void run() {
while (true) {
System.out.println("下载");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MusicThread extends Thread{
@Override
public void run() {
while (true) {
System.out.println("听歌");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
DownloadThread dThread=new DownloadThread();
MusicThread mThread=new MusicThread();
dThread.start();
mThread.start();
}
}
public class DownloadThread extends Thread {
@Override
public void run() {
while (true) {
try {
System.out.println("下载");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MusicThread extends Thread {
@Override
public void run() {
while (true) {
try {
System.out.println("听歌");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行方法
public static void main(String[] args) {
new DownloadThread().start();
new MusicThread().start();
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!