• thread_线程创建


    创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口。

    这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果

    转自 :http://www.cnblogs.com/dolphin0520/p/3949310.html

    1.Thread创建线程

    public class ThreadTest {
    
        public static void main(String[] args) {
            //创建Thread子类的一个实例并重写run方法
            MyThread myThread = new MyThread();
            myThread.start();
    
            // 创建一个Thread的匿名子类:
            Thread thread = new Thread() {
                public void run() {
                    System.out.println("Thread Running");
                }
            };
            thread.start();
            
            //
             System.out.println(Thread.currentThread().getName());
              for(int i=0; i<10; i++){
                 new Thread(" name" + i){
                    public void run(){
                     System.out.println("Thread: " + getName() + " running");
                    }
                 }.start();
              }        
            
        }
    }
    
    class MyThread extends Thread {
        public void run() {
            System.out.println("MyThread running");
        }
    }

    2.Runnable创建线程

    public class RunnableTest {
    
        public static void main(String[] args) {
            //自定义类实现Runnable接口
            Runnable myRunnable = new Runnable() {
                public void run() {
                    System.out.println("myRunnable running ");
                }
            };
            Thread thread1 = new Thread(myRunnable);
            thread1.start();
            
            //匿名
            Thread thread2 = new Thread(
                    new Runnable() {
                        public void run() {
                            System.out.println("匿名 Runnable running ");
                        }
                    });
            thread2.start();        
        }
    }

    3.Callable Future创建线程,Callable和Future,通过它们可以在任务执行完毕之后得到任务执行结果 

    public class CallableFutureTest {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newCachedThreadPool();
            Task task = new Task();
            Future<Integer> result = executor.submit(task);
            executor.shutdown();
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
    
            System.out.println("主线程在执行任务");
            // isDone方法表示任务是否已经完成,若任务完成,则返回true;
            // get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;
            // get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
            //isCancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。
            try {
                System.out.println("status :" + result.isDone());
                System.out.println("task运行结果" + result.get());
                System.out.println("status :" + result.isDone());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println("所有任务执行完毕");
        }
    }
    
    class Task implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(3000);
            int sum = 0;
            for (int i = 0; i < 100; i++)
                sum += i;
            return sum;
        }
    }

    3.Callable FutureTask创建线程 

        RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

    public class CallableFutureTaskTest {
    
        public static void main(String[] args) {
            //第一种方式
            ExecutorService executor = Executors.newCachedThreadPool();
            Task1 task = new Task1();
            FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
    
            executor.submit(futureTask);
            executor.shutdown();
             
            //第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
            /*Task task = new Task();
            FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
            Thread thread = new Thread(futureTask);
            thread.start();*/
             
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
             
            System.out.println("主线程在执行任务");
             
            try {
                System.out.println("task运行结果"+futureTask.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
             
            System.out.println("所有任务执行完毕");
        }
    }
  • 相关阅读:
    Agile方法
    电子书下载:Beginning Nokia Apps Development: Using MeeGo, Mobile QT and OpenSymbian
    电子书下载:Pro Oracle SQL
    电子书下载:Algorithms of the Intelligent Web
    BlogEngine .NET 日期控件显示问题
    电子书下载:Beginning JavaScript, 4th Edition
    电子书下载:Sams Teach Yourself iPhone Application Development in 24 Hours, 2nd Edition
    电子书下载:Pro ASP.NET 4 in VB 2010, 3rd Edition
    电子书下载:MCTS SelfPaced Training Kit (Exam 70515): Web Applications Development with Microsoft .NET Framework 4
    电子书下载:Unity 3D Game Development by Example: Beginner’s Guide
  • 原文地址:https://www.cnblogs.com/dengzy/p/5798822.html
Copyright © 2020-2023  润新知