java多线程的使用1

方式1:

public class LiftOff implements Runnable {
    protected int countDown = 10;
    private static int taskCount = 0;
    private final int id = taskCount++;

    public LiftOff() {
        System.out.println("LiftOff Start:"+Thread.currentThread().getId());
    }

    public LiftOff(int countDown) {
        this.countDown = countDown;
    }

    public String status() {
        System.out.println("LiftOff tid:"+Thread.currentThread().getId());
        return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "),";
    }

    public void run() {
        
        while (countDown-- > 0) {
//            System.out.print();
            status();
            //Thread.yield();
        }
        System.out.println("LiftOff End:"+Thread.currentThread().getId());
    }

}
public class BasicThreads {
    
    public static void main(String[] args){
        System.out.println("main tid:"+Thread.currentThread().getId());
        Thread t=new Thread(new LiftOff());
        t.start();
        System.out.println("Waiting for LiftOff");
    }
}

 

方式2(首选):

 不限制数量的线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class CachedThreadPool {

    public static void main(String[] args) {
        ExecutorService exec=Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            exec.execute(new LiftOff());
        }
        exec.shutdown();
    }
}

 

方式3:

限制数量的线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class FixedThreadPool {
    public static void main(String[] args) {
        ExecutorService exec=Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            exec.execute(new LiftOff());
        }
        exec.shutdown();
    }
}

 

 方式4:

线程顺序执行

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SingleThreadExecutor {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            exec.execute(new LiftOff());
        }
        exec.shutdown();
    }
}

 

方式5:

调用线程并返回结果

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class TaskWithResult implements Callable<String> {
    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    public String call() {
        return "result of TaskWithResult " + id;
    }
}

public class CallableDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService exec = Executors.newCachedThreadPool();
        System.out.println(exec.submit(new TaskWithResult(50)).get());
        ArrayList<Future<String>> results = new ArrayList<Future<String>>();
        for (int i = 0; i < 10; i++) {
            results.add(exec.submit(new TaskWithResult(i)));
        }
        for (Future<String> fs : results) {
            try {
                System.out.println(fs.get());
            } catch (InterruptedException e) {
                System.out.println(e);
                return;
            } catch (ExecutionException e) {
                System.out.println(e);
            } finally {
                exec.shutdown();
            }
        }
    }

}

 

方式6:

后台线程,当主线程退出时(非后台线程),后台线程也自动退出

import java.util.concurrent.TimeUnit;

public class SimpleDaemons implements Runnable{

    public void run() {
        try {
            while (true) {
                TimeUnit.MICROSECONDS.sleep(100);
                System.out.println(Thread.currentThread()+" "+this);
                //print(Thread.currentThread()+" "+this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
//        for (int i = 0; i < 10; i++) {
            Thread daemon=new Thread(new SimpleDaemons());
            daemon.setDaemon(true);
            daemon.start();
//        }
        System.out.println("All daemons started");
        TimeUnit.MICROSECONDS.sleep(175);
        System.out.println("All daemons end");
    }
}

 

方式7:

后台线程的第二种写法

import java.util.concurrent.ThreadFactory;


public class DaemonThreadFactory implements ThreadFactory{

    @Override
    public Thread newThread(Runnable r) {
        Thread t=new Thread(r);
        t.setDaemon(true);
        return t;
    }
    
    
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class DaemonFromFactory implements Runnable{
    public void run() {
        try {
            while (true) {
                TimeUnit.MICROSECONDS.sleep(100);
                System.out.println(Thread.currentThread()+" "+this);
            }
        } catch (Exception e) {
            System.out.println("Interrupted");
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec=Executors.newCachedThreadPool(new DaemonThreadFactory());
        for (int i = 0; i < 10; i++) {
            exec.execute(new DaemonFromFactory());
        }
        System.out.println("All daemons started");
        TimeUnit.MILLISECONDS.sleep(500);
    }
}

 

方式8:

通过继承Thread类

public class SimpleThread extends Thread {

    private int countDown = 5;
    private static int threadCount = 0;

    public SimpleThread() {
        super(Integer.toString(++threadCount));
        start();
    }

    public String toString() {
        return "#" + getName() + "(" + countDown + "),";
    }
    
    public void run() {
        while (true) {
            System.out.println(this);
            if(--countDown==0)
                return;
        }
    }
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new SimpleThread();
        }
    }
}

 

方式9:

匿名内部类

import java.util.concurrent.TimeUnit;

class InnerThread1 {
    private int countDown = 5;
    private Inner inner;

    private class Inner extends Thread {
        Inner(String name) {
            super(name);
            start();
        }

        public void run() {
            try {
                while (true) {
                    System.out.println(this);
                    if (--countDown == 0)
                        return;
                    sleep(10);
                }
            } catch (Exception e) {
                System.out.println("interrupted");
            }
        }

        public String toString() {
            return getName() + ":" + countDown;
        }
    }

    public InnerThread1(String name) {
        inner = new Inner(name);
    }
}

class InnerThread2 {
    private int countDown = 5;
    private Thread t;

    public InnerThread2(String name) {
        t = new Thread(name) {
            public void run() {
                try {
                    while (true) {
                        System.out.println(this);
                        if (--countDown == 0)
                            return;
                        sleep(10);
                    }
                } catch (Exception e) {
                    System.out.println("sleep() interrupted");
                }
            }
        };
        t.start();
    }
}

class InnerRunnable1 {
    private int countDown = 5;
    private Inner inner;

    private class Inner implements Runnable {
        Thread t;

        Inner(String name) {
            t = new Thread(this, name);
            t.start();
        }

        public void run() {
            try {
                while (true) {
                    System.out.println(this);
                    if (--countDown == 0)
                        return;
                    TimeUnit.MILLISECONDS.sleep(10);
                }
            } catch (Exception e) {
                System.out.println("sleep() interrupted");
            }
        }

        public String toString() {
            return t.getName() + ":" + countDown;
        }
    }

    public InnerRunnable1(String name) {
        inner = new Inner(name);
    }
}

class InnerRunnable2 {
    private int countDown = 5;
    private Thread t;

    public InnerRunnable2(String name) {
        t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        System.out.println(this);
                        if (--countDown == 0)
                            return;
                        TimeUnit.MICROSECONDS.sleep(10);
                    }
                } catch (Exception e) {
                    System.out.println("sleep() interrupted");
                }
            }

            public String toString() {
                return Thread.currentThread().getName() + ":" + countDown;
            }
        }, name);
        t.start();
    }
}

class ThreadMethod {
    private int countDown = 5;
    private Thread t;
    private String name;

    public ThreadMethod(String name) {
        this.name = name;
    }

    public void runTask() {
        if (t == null) {
            t = new Thread(name) {
                public void run() {
                    try {
                        while (true) {
                            System.out.println(this);
                            if (--countDown == 0)
                                return;
                            sleep(10);
                        }
                    } catch (Exception e) {
                        System.out.println("sleep() interrupted");
                    }
                }

                public String toString() {
                    return getName() + ":" + countDown;
                }
            };
            t.start();
        }
    }
}

public class ThreadVariations {
    public static void main(String[] args) {
        new InnerThread1("InnerThread1");
        new InnerThread2("InnerThread2");
        new InnerRunnable1("InnerRunnable1");
        new InnerRunnable2("InnerRunnable2");
        new ThreadMethod("ThreadMethod").runTask();
    }
}

 

posted on 2014-03-09 17:31  上校  阅读(327)  评论(0编辑  收藏  举报