这是两个线程交替进行的小程序 不过好像死锁了 有大牛帮看看 并给说明下原因吗?
新手求教 自学java。。。 书本上说的不详细 基本自己摸索的程序就一直停在这里了,好像是两个支线线程都在等待
这是代码:
程序代码:
import java.util.*; class TimeOutput extends Thread { public static volatile boolean stop = false; public TimeOutput() { System.out.println("Branch thread begin..."); } public void run () { System.out.println("Branch thread runnable..."); while (!stop) { synchronized (this) { try { System.out.println("Branch thread notify others..."); notifyAll(); System.out.println("Branch thread waiting..."); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Calendar temp = Calendar.getInstance(); System.out.println(temp.get(Calendar.YEAR) + " : " + temp.get(Calendar.MONTH) + " : " + temp.get(Calendar.DAY_OF_MONTH) + " " + temp.get(Calendar.HOUR_OF_DAY) + " : " + temp.get(Calendar.MINUTE) + " : " + temp.get(Calendar.SECOND)); } System.out.println("Branch thread ended"); } } class PriNumJudge extends Thread { public PriNumJudge() { System.out.println("Main thread begin..."); } public void judgement(int temp) { System.out.println("Judge " + temp + " is a prime number or not."); boolean flag = true; if (temp < 2) { System.out.println("Judgement input number error."); } else if ((2 == temp) || (3 == temp)) { System.out.println(temp + " is a prime number."); } else { for (int i = 2; i <= Math.sqrt(temp); i++) { if (temp % i == 0) { flag = false; break; } } if (flag) { System.out.println(temp + " is a prime number."); } else { System.out.println(temp + " isn't a prime number."); } } System.out.println("Judge " + temp + " completed."); } public void run() { System.out.println("Main thread runable..."); synchronized (this) { for (int i = 1; i < 100; i++) { try { System.out.println("Main thread notify others..."); notifyAll(); System.out.println("Main thread waiting..."); wait(); } catch (InterruptedException e) { e.printStackTrace(); } this.judgement(i); } System.out.println("Change loop condition..."); TimeOutput.stop = true; } System.out.println("Main thread ended."); } } public class Test4 { public static void main(String[] args) { System.out.println("Main method begin..."); PriNumJudge mainThread = new PriNumJudge(); mainThread.start(); TimeOutput branchThread = new TimeOutput(); branchThread.start(); System.out.println("Main method ended"); } }