我需要创建2个线程来掷骰子并在dos中打印。这是我的代码: --class thread -
package dice.application;
enter code here
import java.util.Random;
public class thread1
{
private final int sleepTime;
private final String taskName;
private final int fdice;
private final static Random generator=new Random();
Random randomdie = new Random();
public thread1(String name,int dice)
{
taskName=name;
sleepTime=generator.nextInt(5000);
dice=1+randomdie.nextInt(6);
fdice=dice;
}
public void run()
{
try
{
System.out.printf("%s going to sleep for %d milliseconds.\n",taskName,sleepTime);
Thread.sleep(sleepTime);
System.out.printf("%s rolled : ",fdice);
}
catch(InterruptedException exception)
{
System.out.printf("%s %s\n", taskName,"terminated prematurely due to interruption");
}
System.out.printf("%s done sleeping\n",taskName);
}
}
public class DiceApplication {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereThread player1=new Thread(new PrintTask("roll1"));
Thread player1=new Thread(new thread1("",));
player1.start();
}
}
我在main中遇到一个错误,说我还需要一个整数。 我是java和编程的新手,任何帮助都将非常感激。 感谢
答案 0 :(得分:2)
你的线程类必须实现Runnable public class thread1 implements Runnable
所以它能够以那种方式运行
在这里查看创建线程的两种方法:"implements Runnable" vs. "extends Thread"