java 多线程编程

来源:互联网 发布:西安软件新城附近楼盘 编辑:程序博客网 时间:2024/06/14 12:17

1.通过Thread实现多线程

1.1 Thread thread = new Thread(){run(){}};

/* 该例子的目的是让一个方法在规定的时间内执行完毕,如果没有执行完毕就直接中断 *//** * 这个方法是目标方法,是要在规定时间内完成的方法 * @return * @throws InterruptedException */public boolean test2_() throws InterruptedException{    System.out.println("test2_()方法要执行的方法");    Thread.sleep(3000);// 睡眠等待三秒    return true;// 执行成功,返回true}@Testpublic void test2() throws InterruptedException{    // 创建一个线程,重写run方法    Thread thread = new Thread(){        // 定义成员变量,方便接收目标方法的返回值        public boolean flag = false;        // 重写run方法        @Override        public void run() {            try {                // 开始执行目标方法,并用成员变量接收返回值                flag = test2_();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        // 重写isInterrupted方法,目的是根据成员变量判断test2_()方法是否执行完成        @Override        public boolean isInterrupted() {            return flag;        }    };    // 开启线程并执行    thread.start();    // 规定目标方法1秒钟执行完毕    Thread.sleep(1000);    // 判断目标方法是否执行完成    boolean interrupted = thread.isInterrupted();    // 执行相应操作    if (interrupted) {        System.out.println(thread.getName()+"\t"+thread.getId()+"\t"+"执行完成");    }else {        System.out.println(thread.getName()+"\t"+thread.getId()+"\t"+"执行失败,开始终止线程");        thread.interrupt();        System.out.println(thread.getName()+"\t"+thread.getId()+"\t"+"执行失败,终止线程完成");    }}

1.2 class ThreadChild extends Thread

public class ThreadExtendsThread extends Thread{    @Override    public void run() {    }}

1.3 Thread 常用的方法

// 获取线程名称public static String getThreadName(Thread thread){    return thread.getName();}// 获取线程进程号public static Long getThreadId(Thread thread){    return thread.getId();}// 为进程设置名称public static void setThreadName(Thread thread,String threadName) {    thread.setName(threadName);}// 中断线程public static Object killThreadByName(Thread thread) {    thread.interrupt();    // 判断线程是否中断    boolean interrupted = thread.interrupted();    return interrupted;}

2. 通过Runnable的方式实现

Thread thread = new Thread(new Runnable() {    public void run() {        // TODO Auto-generated method stub    }});thread.start();
原创粉丝点击