목표 : 우선 순위가 높은 스레드와 우선 순위가 낮은 스레드가 몇 번 액세스되었는지를 계산하려고합니다. // 다음 코드를 컴파일하면 'h'(int h high)는 0이지만 'l'(low)가 증가합니다. 다음과 같이 실행 코드스레드 우선 순위 계산 - Java
class Priority implements Runnable {
int high = 0;
int low = 0;
int count; Thread thrd;
static boolean stop = false;
static String currentName;
Priority(String name) {
thrd = new Thread(this, name);
count = 0;
currentName = name;
}
public void run() {
System.out.println(thrd.getName() + " starting.");
do {
count++;
if(currentName.compareTo(thrd.getName()) != 0) {
currentName = thrd.getName();
System.out.println("In " + currentName);
System.out.println("Name in thrd is " + thrd.getName());
System.out.println("name in currentName is " + currentName);
if ("High Priority" == currentName) h++;
if ("Low Priority" == currentName) l++;
}
} while(stop == false && count<10);
stop = true;
System.out.println("\n" + thrd.getName() + " terminating.");
}
}
class PriorityDemo {
public static void main(String args[]) {
Priority mt1 = new Priority("High Priority");
Priority mt2 = new Priority("Low Priority");
mt1.thrd.setPriority(Thread.NORM_PRIORITY+2);
mt2.thrd.setPriority(Thread.NORM_PRIORITY-2);
mt1.thrd.start();
mt2.thrd.start();
try {
mt1.thrd.join();
mt2.thrd.join();
} catch(InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("\n High priority thread counted to " + mt1.count);
System.out.println("'n Low priority thread counted to " + mt2.count);
System.out.println("In 'mt1' \nhigh is " + mt1.h + " and low is " + mt1.l);
System.out.println("In 'mt2' \nhigh is " + mt2.h + " and low is " + mt2.l);
}
}
마지막 두 라인은 : MT1에서 높은 인 0 낮다 (예컨대 위해) MT2 높은 985 로우가 985 인 0있다!
나는 또한 시도했다 // if ("High Priority"== thrd.getName()) h ++; if ("낮은 우선 순위"== thrd.getName()) l ++; 하지만 이것도 효과가 없었습니다.
사용 "높은 우선 순위"입니다 .equals (thrd.getName()) – tgkprog
또는 "높은 우선 순위"를 나타내는 열거 형 또는 최종 문자열/int ... – tgkprog
이것은 너무 버그가있는 것처럼 보입니다. if (currentName.compareTo (thrd.getName())! = 0) { currentName = thrd.getName(); 다른 것은 스레드 프로그램은 재미 있지만 대부분의 앱 개발자에게는 쓸모가 없다는 것입니다. j2ee 및 컬렉션에 중점을 둡니다 ...학교와 학업 성적이 – tgkprog