Threads ThreadLister erstellen

chrilux

Mitglied
Hallo,

sitzen hier zur Klausurvorbereitung und sind an einer Aufgabe angekommen, die wir mal gar nicht verstehen....


Vielleicht kann einer Hilfestellung geben?? Allein erstmal das Verständnis was wir hier überhaupt tun sollen.

Irgendwie steige ich da nicht durch...
 

Anhänge

  • HA.jpg
    HA.jpg
    128,4 KB · Aufrufe: 21

anti-held

Bekanntes Mitglied
Sollte in etwa so aussehen:

Java:
public class ThreadListener {

	public static void main(String[] args) {
		System.out.println(allThreadsToString());
	}

	public static String allThreadsToString() {
		// get root threadgroup
		Thread thread = Thread.currentThread();
		ThreadGroup nextThread = thread.getThreadGroup();
		ThreadGroup root = null;
		while (nextThread != null) {
			nextThread = nextThread.getParent();
			if (nextThread != null) {
				root = nextThread;
			}
		}

		StringBuilder sb = new StringBuilder();
		sb.append(printThreadGroup(root));
		return sb.toString();
	}
	
	private static String printThreadGroup(ThreadGroup group){
		return printThreadGroup(group, 0);
	}

	private static String printThreadGroup(ThreadGroup group, int depth) {
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i<depth;i++){
			sb.append("\t");
		}
		sb.append("ThreadGroup: ").append(group.getName()).append(" MaxPriority: ").append(group.getMaxPriority()).append("\n");

		// append subthreads
		int size = 5;
		Thread[] threads = new Thread[size];
		int count = group.enumerate(threads);
		if (count > size) {
			threads = new Thread[count];
			group.enumerate(threads);
		}
		for (Thread thread : threads) {
			if (thread != null && thread.getThreadGroup() == group) {
				sb.append(printThread(thread, depth +1));
			}
		}

		// append subgroups
		ThreadGroup[] groups = new ThreadGroup[size];
		count = group.enumerate(groups);
		if (count > size) {
			groups = new ThreadGroup[count];
			group.enumerate(groups);
		}
		for (ThreadGroup currentGroup : groups) {
			if (currentGroup != null) {
				sb.append(printThreadGroup(currentGroup, depth + 1));
			}
		}

		return sb.toString();
	}

	private static String printThread(Thread thread, int depth) {
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i<depth;i++){
			sb.append("\t");
		}
		sb.append("Thread: ").append(thread.getName()).append(" Priority: ").append(thread.getPriority()).append(" Dämon: ").append(thread.isDaemon()).append("\n");
		return sb.toString();
	}
}
 

Neue Themen


Oben