从事班级作业,我正在努力完成它。
这需要是线程安全的并可以运行。
我需要创建2个得分对象,这些得分对象被初始化为唯一ID和初始得分100。然后需要创建20个线程,并将5个线程分配给第一个对象的增量器,将5个线程分配给第一个对象的减量器,以及一个附加对象每个第二个对象5个线程。
class ScoreRunnerDemo implements Runnable
{
private long id = 1;
private double score = 100;
Thread t1;
// Count()
{
t1 = new Thread(this, "Runnable Thread")
System.out.println("created thread " + t1);
t1.start();
}
public void run ()
{
try
{
for (int i = 0; i<5; i++) {
System.out.println("Printing the count " + i);
Thread.sleep(100);
}
}
catch (InterruptedException e)
{
System.out.println("first increment thread
interrupted");
}
System.out.println("t1 is over");
}
}
public class ScoreRunner
{
public static void main(String[] args) {
//number of threads
int n = 20;
for (int i = 0; i < n; i++) {
ScoreRunnerDemo object = new ScoreRunnerDemo();
while (ScoreRunnerDemo.getScore < 200) {
System.out.println("Thread: " +
Thread.currentThread().getId() + " Score: " + ScoreRunner.());
}
}
}
请帮助,因为我不确定我还需要什么。
Score类如下:
import java.text.DecimalFormat;
public class Score
{
private long id;
private double score;
private DecimalFormat df = new DecimalFormat("#,###.##");
/**Grade
* @param id
* @param score
*/
public Score(long id, double score)
{
this.id = id;
this.score = score;
}
/** Method getId
* @return
*/
public long getId()
{
return id;
}
/** Method setId
* @param id
*/
public void setId(long id)
{
this.id = id;
}
/** Method getScore
* @return
*/
public double getScore()
{
return score;
}
/** Method setScore
* @param score
*/
public void setScore(double score)
{
this.score = score;
}
public synchronized void updateScore(double change)
{
score += change;
System.out.println("ID: " + id + "\t" + " Score: " + df.format(score));
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return id + "\t" + "\t" + score;
}
}