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
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
推荐阅读
- 药品价格315网正规吗 – 好315网是正规网站吗
- 大数据码获取方法 目前开源免费数据库有哪些
- 昆明网站定制 昆明网站优化
- 如何做网站建设方案,网站建设五个基本流程
- 免费查询大数据征信 征信大数据
- 现在免费的创业致富 创业致富的好门路
- 免费手机通话录音软件 电话录音软件
- 免费教你4种分组技巧 微信怎么分组管理好友
- 拼多多砍价网站 拼多多砍价1元10刀网站
- 免费破解pdf加密文件 pdf免费解密方法有什么