实现Runnable并扩展线程
我被赋予运行两个线程的任务,一个使用 extends,一个使用 Implements runnable,输出类似于此 F(0) F(1) F(2) ………… S(0) S(1) S(2)
到目前为止我得到 F(0) S(1) F(1) F(2) S(2)
public class Fast implements Runnable
{
/** Creates a new instance of Fast */
public void run()
{
for(int i = 0; i <= 9; i++)
{
try
{
System.out.println("F("+ i + ")");
Thread.sleep(200);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
和
public class Slow extends Thread
{
/** Creates a new instance of Slow */
public void run()
{
for(int i = 0; i <= 6; i++)
{
try
{
System.out.println("S("+ i + ")");
Thread.sleep(400);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
与主
public class Main
{
public static void main(String args[])
{
Fast f = new Fast();
Slow s = new Slow();
Thread ft = new Thread(f);
ft.start();
s.start();
}
}
I have been given the task of running two threads one using extends and one using implements runnable, the output is meant to be similair to this
F(0)
F(1)
F(2)
.........
S(0)
S(1)
S(2)
So far im getting
F(0)
S(1)
F(1)
F(2)
S(2)
public class Fast implements Runnable
{
/** Creates a new instance of Fast */
public void run()
{
for(int i = 0; i <= 9; i++)
{
try
{
System.out.println("F("+ i + ")");
Thread.sleep(200);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
and
public class Slow extends Thread
{
/** Creates a new instance of Slow */
public void run()
{
for(int i = 0; i <= 6; i++)
{
try
{
System.out.println("S("+ i + ")");
Thread.sleep(400);
}
catch(InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error" + errMessage);
}
}
}
}
With the main
public class Main
{
public static void main(String args[])
{
Fast f = new Fast();
Slow s = new Slow();
Thread ft = new Thread(f);
ft.start();
s.start();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来你想让Slow跑在Fast之后?你的输出几乎是我所期望的。最终 F 将更快完成(仅 2000 毫秒),而 S 仍将运行(2800 毫秒)。我不是这个任务与实现 Runnable 或扩展 Thread 有关的事情,因为它们给你相同的最终结果。
如果您希望 F 在 S 之前完全完成,您需要首先加入 F,如下所示:
在启动 S 之前,它将等待 ft 完成,从而为您提供所需的输出 F1,F2,... S1,S2,...
It seems like you want to get Slow to run after Fast? Your output is pretty much what i would expect. Eventually F will finish faster (just 2000ms) and S will still be running (2800ms). I'm not what this assignment has got to do with implementing Runnable or extending Thread since they give you the same end-result.
If you want F to finish completely before S you need to join on F first, like this:
That will wait for ft to complete before even starting S giving you the desired output F1, F2,... S1,S2,...