JAvaマルチスレッドプログラミング--ウサギの競走過程をシミュレートする
3955 ワード
マルチスレッドプログラミングを習い始めたばかりで、授業中もまじめに聞いていなかったので、授業の下でネット上でPPTを探して、またまじめに勉強しました.
質問:
問題①
Animalクラス:
public class Animal extends Thread{
public Animal(String name){
super(name);
}
public void run(){
for(int i=0;i<=100;i+=10){
if(this.getName().equals(" "))
System.out.println(" "+ i + " ");
else
System.out.println(" "+ i + " ");
}
try{
Thread.sleep((long)(Math.random()*1000));
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
テストクラス:
public class Quetion1 {
public static void main(String[] args) {
Animal rabbit = new Animal(" ");
Animal tortoise = new Animal(" ");
rabbit.start();
tortoise.start();
}
}
問題②
Animalクラス:
public class Animal implements Runnable{
private String name;
public Animal(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void run(){
for(int i=0;i<=100;i+=10){
if(this.getName().equals(" "))
System.out.println(" "+ i + " ");
else
System.out.println(" "+ i + " ");
}
try{
Thread.sleep((long)(Math.random()*1000));
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
テストクラス:
public class Quetion2 {
public static void main(String[] args) {
Animal rabbit = new Animal(" ");
Animal tortoise = new Animal(" ");
Thread t1 = new Thread(rabbit);
Thread t2 = new Thread(tortoise);
t1.start();
t2.start();
}
}
質問③
Animalクラス:
public class Animal extends Thread{
public Animal(String name) {
super(name);
}
public void run() {
for(int i=0;i<=100;i+=10) {
if(this.getName().equals(" "))
System.out.println(" " + i + " ");
else
System.out.println(" " + i + " ");
}
}
}
テストクラス:
public class Question3 {
public static void main(String[] args) {
Animal rabbit = new Animal(" ");
Animal tortoise = new Animal(" ");
rabbit.setPriority(1);
tortoise.setPriority(10);
rabbit.start();
tortoise.start();
}
}
質問④
Animalクラス:
public class Animal implements Runnable{
Thread rabbit,tortoise;
public Animal() {
rabbit = new Thread(this," ");
tortoise = new Thread(this," ");
}
public void run() {
if(Thread.currentThread() == tortoise) {
System.out.println(" , 。 : !");
rabbit.interrupt();
System.out.println(" ...");
}
else {
try{
System.out.println(" ... ");
rabbit.sleep(1000*60);
}
catch(InterruptedException e) {
System.out.println(" ");
System.out.println(" ");
}
}
}
}
テストクラス:
public class Question4 {
public static void main(String[] args) {
Animal animal = new Animal();
System.out.println(" :");
System.out.println(" : " + animal.rabbit.getState());
System.out.println(" : " + animal.tortoise.getState());
System.out.println(" :");
animal.rabbit.start();
animal.tortoise.start();
System.out.println(" : " + animal.rabbit.getState());
System.out.println(" : " + animal.tortoise.getState());
System.out.println(" : " + Thread.activeCount());
/* 3, */
}
}