本文共 6707 字,大约阅读时间需要 22 分钟。
搞起一个有意思的..
了解下多线程可以干嘛
第一个多线程展示一个有意思的多线程
第二个多线程展示怎么轮询每个多线程是否结束
第一多线程:
package cn.edu.xmu.dm.mt;import java.io.*;//多线程编程 public class MultiThread { public static void main(String args[]) { System.out.println("我是主线程!"); // 下面创建线程实例thread1 ThreadUseExtends thread1 = new ThreadUseExtends(); // 创建thread2时以实现了Runnable接口的THhreadUseRunnable类实例为参数 Thread thread2 = new Thread(new ThreadUseRunnable(), "SecondThread"); thread1.start();// 启动线程thread1使之处于就绪状态 // thread1.setPriority(6);//设置thread1的优先级为6 // 优先级将决定cpu空出时,处于就绪状态的线程谁先占领cpu开始运行 // 优先级范围1到10,MIN_PRIORITY,MAX_PRIORITY,NORM_PAIORITY // 新线程继承创建她的父线程优先级,父线程通常有普通优先级即5NORM_PRIORITY System.out.println("主线程将挂起7秒!"); try { Thread.sleep(7000);// 主线程挂起7秒 } catch (InterruptedException e) { return; } System.out.println("又回到了主线程!"); if (thread1.isAlive()) { thread1.stop();// 如果thread1还存在则杀掉他 System.out.println("thread1休眠过长,主线程杀掉了thread1!"); System.out.println("---------------thread1 kill" + thread1.getValue()); } else{ System.out.println("---------------thread1 stop" + thread1.getValue()); System.out.println("主线程没发现thread1,thread1已醒顺序执行结束了!"); } thread2.start();// 启动thread2 System.out.println("主线程又将挂起7秒!"); try { Thread.sleep(7000);// 主线程挂起7秒 } catch (InterruptedException e) { return; } System.out.println("又回到了主线程!"); if (thread2.isAlive()) { thread2.stop();// 如果thread2还存在则杀掉他 System.out.println("thread2休眠过长,主线程杀掉了thread2!"); } else System.out.println("主线程没发现thread2,thread2已醒顺序执行结束了!"); System.out.println("程序结束按任意键继续!"); try { System.in.read(); } catch (IOException e) { System.out.println(e.toString()); } }// main}// MultiThreadclass ThreadUseExtends extends Thread// 通过继承Thread类,并实现它的抽象方法run()// 适当时候创建这一Thread子类的实例来实现多线程机制// 一个线程启动后(也即进入就绪状态)一旦获得CPU将自动调用它的run()方法{ private double value; ThreadUseExtends() { }// 构造函数 public void run() { System.out.println("我是Thread子类的线程实例!"); System.out.println("我将挂起10秒!"); System.out.println("回到主线程,请稍等,刚才主线程挂起可能还没醒过来!"); try { value = 10; sleep(10000);// 挂起5秒 } catch (InterruptedException e) { return; } // 如果该run()方法顺序执行完了,线程将自动结束,而不会被主线程杀掉 // 但如果休眠时间过长,则线程还存活,可能被stop()杀掉 } public double getValue() { return value; } public void setValue(double value) { this.value = value; } }class ThreadUseRunnable implements Runnable// 通过实现Runnable接口中的run()方法,再以这个实现了run()方法的类// 为参数创建Thread的线程实例{ private double value; // Thread thread2=new Thread(this); // 以这个实现了Runnable接口中run()方法的类为参数创建Thread类的线程实例 ThreadUseRunnable() { }// 构造函数 public void run() { System.out.println("我是Thread类的线程实例并以实现了Runnable接口的类为参数!"); System.out.println("我将挂起1秒!"); System.out.println("回到主线程,请稍等 jn0-120 e20-040 ,刚才主线程挂起可能还没醒过来!"); try { Thread.sleep(1000);// 挂起5秒 value = 1; } catch (InterruptedException e) { return; } // 如果该run()方法顺序执行完了,线程将自动结束,而不会被主线程杀掉 // 但如果休眠时间过长,则线程还存活,可能被stop()杀掉 } public double getValue() { return value; } public void setValue(double value) { this.value = value; } }// 该程序可做的修改如改休眠时间或优先级setPriority()
package cn.edu.xmu.dm.mt;
import java.io.*;import java.util.concurrent.*;import java.util.*;class MyThreadPoolExecutor extends ThreadPoolExecutor { private boolean hasFinish = false; public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueueworkQueue, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); // TODO Auto-generated constructor stub } public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); // TODO Auto-generated constructor stub } public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); // TODO Auto-generated constructor stub } public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); // TODO Auto-generated constructor stub } /* * (non-Javadoc) * * @see * java.util.concurrent.ThreadPoolExecutor#afterExecute(java.lang.Runnable, * java.lang.Throwable) */ @Override protected void afterExecute(Runnable r, Throwable t) { // TODO Auto-generated method stub super.afterExecute(r, t); synchronized (this) { System.out.println("自动调用了....afterEx 此时getActiveCount()值:" + this.getActiveCount()); if (this.getActiveCount() == 1)// 已执行完任务之后的最后一个线程 { this.hasFinish = true; this.notify(); }// if }// synchronized } public void isEndTask() { synchronized (this) { while (this.hasFinish == false) { System.out.println("等待线程池所有任务结束: wait..."); try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }}
第一个程序结束
第二个程序开始
package cn.edu.xmu.dm.mt;import java.io.File;/** * 统计文件的主类 * @author chenwq * */public class Manager { /** * @param args */ public static void main(String[] args) { File[] roots = File.listRoots();//系统的根目录数组 ThreadListener tl = new ThreadListener();//监听统计文件线程的监控线程 for(int i=0;ipackage cn.edu.xmu.dm.mt;
/** * 统计文件的线程类 */import java.io.File;public class CountFile extends Thread { // 根目录名 private File root; // 标志线程是否执行完毕的属性 private boolean finished; //要输出的信息 String info; // 构造器,传入一个根目录名 public CountFile(File root) { this.root = root; } // 查看线程是否已经执行完毕 public boolean isFinished() { return finished; } // 通过线程进行文件统计 public void run() { System.out.println(root+"盘文件统计开始"); int count = countProcess(root); info = root.getAbsolutePath()+"盘统计文件数为"+count+"\n"; finished = true; System.out.println(root+"盘文件统计完毕"); } private int countProcess(File dir) { int count = 0; if (!dir.exists()) {// 如果该文件指向的地址不存在 return count; } // 将文件中的子文件保存在文件数组中 File[] files = dir.listFiles(); if (files == null) {// 如果文件数组为空,则返回0 return count; } for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) {// 如果是文件夹 count += countProcess(files[i]); } else if (files[i].isFile()) {// 如果是标准文件 count++; } } return count; }}
package cn.edu.xmu.dm.mt;/** * 监视统计线程的线程类 */import java.util.ArrayList;public class ThreadListener extends Thread{ ArrayListarray = new ArrayList (); String result=""; public void run(){ boolean flag=false; while(!flag){ for(int i=0;i
转载地址:http://bvwob.baihongyu.com/