2021-11-23 thread of Java computer experiment

This blog is only a personal learning record and is not guaranteed to be completely accurate

Experiment content:

(1) Create a Thread by inheriting the Thread class

Program template: ThreadExample.java

class Tortoise extends Thread {
	int sleepTime = 0, liveLength = 0;

	Tortoise(int sleepTime, String name, int liveLength) {
		this.sleepTime = sleepTime;
		this.liveLength = liveLength;
		setName(name); // Set the thread name to name
	}

	public void run() {
		while (true) {
			liveLength--;
			System.out.print("@");
			try {
				sleep(sleepTime); // Let the thread call the sleep method to enter the interrupt state. After sleepTime milliseconds, the thread queues up again and waits for CUP resources
			} catch (InterruptedException e) {
			}
			if (liveLength <= 0) {
				System.out.print(getName() + "Enter the state of death\n");
				return; // Statement that ends the run method
			}
		}
	}
}

class Rabbit extends Thread {
	int sleepTime = 0, liveLength;

	Rabbit(int sleepTime, String name, int liveLength) {
		this.sleepTime = sleepTime;
		this.liveLength = liveLength;
		setName(name); // Set the thread name to name
	}

	public void run() {
		while (true) {
			liveLength--;
			System.out.print("*");
			try {
				sleep(sleepTime); // Let the thread call the sleep method to enter the interrupt state. After sleepTime milliseconds, the thread queues up again and waits for CUP resources
			} catch (InterruptedException e) {
			}
			if (liveLength <= 0) {
				System.out.print(getName() + "Enter the state of death\n");
				return; // Statement that ends the run method
			}
		}
	}
}

public class ThreadExample {
	public static void main(String args[]) {
		Rabbit rabit;
		rabit = new Rabbit(4, "a", 3); // New thread rabit
		Tortoise tortoise;
		tortoise = new Tortoise(5, "b", 6); // New thread tortoise
		tortoise.start(); // Start thread tortoise
		rabit.start(); // Start thread rabit
	}
}

Program running results:

The reason why the same object cannot start() twice is:

The state of a thread will be explicitly written into its public internal enumeration type Java.lang.Thread.State, namely: NEW, ready, BLOCKED, WAITING, TIMED_WAIT, and TERMINATED. When the start() method is called the second time, the thread that has been started is no longer in the (NEW) state, so an IllegalThreadStateException will occur

(2) Create a thread by passing a Runnable object to the Thread() constructor

Program template: ShopExample.java

class Shop implements Runnable {
	Thread zhangWorker, wangWorker, boss;

	Shop() {
		boss = new Thread(this); // Create boss, and the Shop object is the target object of boss
		zhangWorker = new Thread(boss); // Create zhangWorker, and the Shop object is the target object of zhangWorker
		wangWorker = new Thread(boss); // Create wangWorker, and the Shop object is the target object of wangWorker
		zhangWorker.setName("Zhang Gong");
		wangWorker.setName("Wang Gong");
		boss.setName("boss");
	}

	public void run() {
		int i = 0;
		if (Thread.currentThread() == zhangWorker) {
			while (true) {
				try {
					i++;
					System.out.println(zhangWorker.getName() + "It has been moved" + i + "Box apple");
					if (i == 3)
						return;
					Thread.sleep(10000);// zhangWorker sleeps for 10 seconds (10000 milliseconds)
				} catch (InterruptedException e) {
					System.out.println(boss.getName() + "Give Way" + zhangWorker.getName() + "Keep working");
				}
			}
		} else if (Thread.currentThread() == wangWorker) {
			while (true) {
				try {
					i++;
					System.out.println(wangWorker.getName() + "It has been moved" + i + "Box banana");
					if (i == 3)
						return;
					Thread.sleep(10000);// wangWorker sleeps for 10 seconds (10000 milliseconds)
				} catch (InterruptedException e) {
					System.out.println(boss.getName() + "Give Way" + wangWorker.getName() + "Keep working");
				}
			}
		} else if (Thread.currentThread() == boss) {
			while (true) {
				zhangWorker.interrupt(); // Wake up zhangWorker
				wangWorker.interrupt(); // Wake up wangWorker
				if (!(wangWorker.isAlive() || zhangWorker.isAlive())) {
					System.out.println(boss.getName() + "go off work");
					return;
				}
			}
		}
	}
}

class ShopExample {
	public static void main(String args[]) {
		Shop shop = new Shop();
		shop.zhangWorker.start();
		shop.wangWorker.start();
		shop.boss.start();
	}
}

Program running results:

  The results of the two runs may be different because:

There are three threads in the shop class, and multithreading in java runs in a preemptive manner. The cpu that preempts the cpu first will allocate time slices to run, so the results are different

(3) Program as required

1. Define the abstract class Animal, and define two behaviors: eat() and move();

2. Realize Cat like, Dog like, Bird like and Falcon like by inheritance;

2.1 eat(): the cat outputs "eat fish", the dog outputs "eat bones", the bird outputs "eat insects", and the Falcon outputs "eat snakes"

2.2 move(): cat outputs "jump", dog outputs "run", bird outputs "fly", and Falcon outputs "fly very high"

3. Define the IPet interface and define the behavior Play();

4. Implement classes PetDog, PetCat and PetRobot;

4.1 Play behavior: PetDog outputs "Frisbee", PetCat outputs "cat", and PetRobot outputs "program and play"

4.2 add the name attribute name and get for the classes PetDog and PetCat_ Name and set_name method

5. Generate the test class Stage, and generate 3 dogs, 2 cats, 1 falcon, 1 bird, 1 pet dog, 1 pet cat and 1 robot pet in the test class;

5.1 name pet cats and dogs

5.2 generate a list, which is used to store all the generated animals. Traverse the list through the iterator to let all animals eat() and move()

5.3 increase the weight attribute for all animals. They will gain weight after eating each time. The weight gain of each animal is based on species and should be random

5.4 ranking animals by weight

5.5 store all pets in the hash table, find out the corresponding objects from the hash table according to the pet name entered by the user, and interact with play()

import java.util.*;

abstract class Animal {
	private int weight = 5;

	public int getWeight() {
		return weight;
	}

	public void setWeight(int w) {
		weight += w;
	}

	public abstract void eat();

	public abstract void move();
}

class Cat extends Animal {
	public void eat() {
		System.out.println("Eat fish");
		setWeight((int) (4 + Math.random() * 2));
	}

	public void move() {
		System.out.println("jump");
	}
}

class Dog extends Animal {
	public void eat() {
		System.out.println("Eat bones");
		setWeight((int) (6 + Math.random() * 3));
	}

	public void move() {
		System.out.println("run");
	}
}

class Bird extends Animal {
	public void eat() {
		System.out.println("Eat worms");
		setWeight((int) (1 + Math.random() * 2));
	}

	public void move() {
		System.out.println("fly");
	}
}

class Falcon extends Animal {
	public void eat() {
		System.out.println("Eat snake");
		setWeight((int) (3 + Math.random() * 2));
	}

	public void move() {
		System.out.println("Fly high");
	}
}

interface IPet {
	public void Play();
}

class PetCat extends Cat implements IPet {
	private String Name;

	public String get_name() {
		return Name;
	}

	void set_name(String name) {
		Name = name;
	}

	public void Play() {
		System.out.println("Roll cat");
	}
}

class PetDog extends Dog implements IPet {
	private String Name;

	public String get_name() {
		return Name;
	}

	void set_name(String name) {
		Name = name;
	}

	public void Play() {
		System.out.println("Holding a Frisbee");
	}
}

class PetRobot implements IPet {
	private String Name;

	PetRobot(String name) {
		Name = name;
	}

	public String get_name() {
		return Name;
	}

	void set_name(String name) {
		Name = name;
	}

	public void Play() {
		System.out.println("Let's play");
	}

}

public class Stage {
	public static void main(String a[]) {
		List<Animal> animalList = new ArrayList<Animal>();
		for (int i = 0; i < 3; i++) {
			animalList.add(new Dog());
		}
		for (int i = 0; i < 2; i++) {
			animalList.add(new Cat());
		}
		animalList.add(new Falcon());
		animalList.add(new Bird());
		PetDog petdog = new PetDog();
		PetCat petcat = new PetCat();
		PetRobot petrobot = new PetRobot("Alma dog");
		petdog.set_name("Wangcai");
		petcat.set_name("nut");
		animalList.add(petdog);
		animalList.add(petcat);

        //Traversing the list through iterators
		Iterator iter = animalList.iterator();
		while (iter.hasNext()) {
			Animal e = (Animal) iter.next();
			e.eat();
			e.move();
		}

        //Sort the animals in the list by weight
		System.out.println("Animal weight ranking:");
		Collections.sort(animalList, new Comparator<Animal>() {
			public int compare(Animal a1, Animal a2) {
				return a1.getWeight() - a2.getWeight();
			}
		});

		for (Animal e : animalList) {
			System.out.print(e.getClass().getSimpleName() + ':');
			System.out.println(e.getWeight());
		}

        //Create a hash table for pets
		HashMap<String, IPet> petHashMap = new HashMap<>();
		petHashMap.put(petdog.get_name(), petdog);
		petHashMap.put(petcat.get_name(), petcat);
		petHashMap.put(petrobot.get_name(), petrobot);
		System.out.println("Please enter pet name:");
		Scanner scanner = new Scanner(System.in);
		String str = scanner.next();
		if (petHashMap.containsKey(str)) {
			petHashMap.get(str).Play();
		}
	}
}

Operation results:

  This record comes here first. There may be supplementary standard answers or the use of some things later

Tags: Java

Posted on Wed, 24 Nov 2021 03:15:53 -0500 by ldsmike88