免费网站java源码大全 java项目案例分析( 二 )


TERMTNATED: 线程执行完毕 。
本节将在一个案例中创建10个线程来找出20000以内的奇数 。
项目准备
本案例是用Eclipse IDE实现的 。如果开发者使用Eclipse或者其他IDE (例如NetBeans ) ,则应打开它并创建一个新的Java项目 。
案例实现
根据如下步骤实现本案例
1,创建一个名为calculator的类,并实现Runnable接口:
Public class Calculator implements Runnable{ 2,实现run()方法 。在这个方法中,存放着线程将要运行的指令 。在这里,这个方法用来计算20000以内的奇数
@Overridepublic void run()long current =1L;long max =20000L;long numPrimes = OL;System.out.printf("Thread \\\'%s\\\': STARTn"Thread.currentThread().getName());while (current <=max)if (isPrime(current)){numPrimes;}current;}System.out.printf("Thread \\\'%s\\\'; END. Number of Primes: %dn"Thread.currentThread() .getName(), numPrimes);} 3.实现辅助方法isprime()。该方法用于判断一个数是否为奇数:
private boolean isPrime (long number) {if (number <=2){return true;}for (long i =2; i 4,实现应用程序的主方法,创建包含main()方法的Main类:
public class Main {public static void main(String[] args) { 5,首先,输出线程的最大值、最小值和默认优先级:
System.out.printf("minimum Priority: %sn",Thread.MIN_PRIORITY);System.out, printf{"Normal Priority: %sn",Thread. NORM_PRIORITY);System.out.printf("Maximun Priority: %sn",Thread.MAX_PRIORITY); 6,创建10个 Thread对象,分别用来执行10个 calculator 任务 。再创建两个数组,用来保存
Thread 对象及其State 对象 。后续我们将用这些信息来查看线程的状态 。这里将5个线程设置为最大优先级,另5个线程设置为最小优先级:
Thread threads [];Thread,state status[];threads = new Threadr10];status = new Thread.Stater[10];for (int i = 0; i < 10; i){threads[i] = new Thread (new Calculator());ir ((i% 2) ==0) {threads [i].setPriority(Thread.MAX_PRIORITY);}else{threads[i].setpriority(Thread.MIN_PRIORITY));}threads[i].setName("My Thread" i);} 7,接着将一些必要的信息保存到文件中,因此需要创建try-with-resources语句来管理文件 。在这个代码块中,先将线程启动前的状态写入文件,然后启动线程:
try (Filewriter file = new Filewriter(".datalog.txt");Printwriter pw = new Printwriter(file);){for (int i =0; i <10; i|){pw.println("Main : Status of Thread " i ":" threads[i].getstate());status[i] = threads[i].getstate();}for (int i =0; i < 10; i){threads[i].start();} 8,等待线程运行结束 。在1.6节中,我们将用join()方法来等待线程结束 。本案例中,由于我们需要记录线程运行过程中状态的转变,因此不能使用join()方法来等待线程结束,而应使用如下代码:
boolean finish = false:while (!finish){for (int i =0; i

推荐阅读