所以尝试完成我的任务,还有一件事对我来说还不顺利。 在此程序中,我使用2个类,这是对运行的压缩, 我只想宣布赢得比赛的球员的位置。
例如:我们有4个线程。 如果第二个线程最后达到100M,我想发布一个他排在第四位的味精。
赛车手等级
mallopt(M_ARENA_MAX, 1);
Track类:
package assig1_2;
public class Racer extends Thread{
public static int globalid = 1;
private int id;
private int speed;
private Track track;
public Racer(int Speed,Track track) {
this.speed = Speed;
this.track = track;
this.id = this.globalid;
this.globalid++;
}
public void run() {
go ();
}
void go () {
this.track.setPriority(this.speed);
for(int i=1; i<=10; i++) {
System.out.println("runner " + this.id + " run " + i + " meters " );
if (i == 10) {
this.track.setPlace(id);
System.out.println("Runner " + this.id + " finished " + track.getPlaceNumber() + track.getPlaceName() );
}
}
}
}
在使用Thread的第一课中,它的愚蠢程序。
答案 0 :(得分:1)
我没有对您的程序进行任何更改,并引入了AtomicInteger和ExecutorService。 跟踪类未进行任何更改。
public class Racer extends Thread {
private static AtomicInteger atomicInteger = new AtomicInteger(0);
private int id;
private int speed;
private Track track;
private Racer(){}
public Racer(int Speed, Track track) {
this.speed = Speed;
this.track = track;
}
public int getPosition(){
return atomicInteger.incrementAndGet();
}
public static void main(String[] args) throws InterruptedException {
ExecutorService service = null;
service = Executors.newFixedThreadPool(4);
for (int i = 1; i <= 4; i++) {
service.execute(() -> {
new Racer(1, new Track()).go();
});
}
service.awaitTermination(3, TimeUnit.SECONDS);
if (service != null) service.shutdown();
}
void go() {
this.track.setPriority(this.speed);
for (int i = 1; i <= 10; i++) {
System.out.println("runner " + Thread.currentThread().getName().substring(7,15) + " run " + i + " meters ");
if (i == 10) {
this.track.setPlace(getPosition());
System.out.println("Runner " + Thread.currentThread().getName().substring(7,15) + " finished " +track.getPlaceNumber() +" "+ track.getPlaceName() );
}
}
} }
答案 1 :(得分:0)
这是主要的。 而且我们无法在其中进行更改。
package assig1_2;
公共类assig1_2_main {
public static void main(String[] args){
Track track = new Track();
Racer racer1 = new Racer(10, track);
Racer racer2 = new Racer(2, track);
Racer racer3 = new Racer(3, track);
Racer racer4 = new Racer(7, track);
Thread t1 = new Thread(racer1);
Thread t2 = new Thread(racer2);
Thread t3 = new Thread(racer3);
Thread t4 = new Thread(racer4);
t1.start();
t2.start();
t3.start();
t4.start();
}
}