Fork me on GitHub

Java中线程和线程池

Java中开启多线程的三种方式

1、通过继承Thread实现

public class ThreadDemo extends Thread{
    public void run(){
        System.out.println("extends Thread");
    }

}

ThreadDemo th=new ThreadDemo();
th.start();

2、implements Runnable 这种方式使用较多,面向接口可以多实现

public class ThreadRunableDemo implements Runnable {
    public void run() {
        System.out.println("implements Runnable");
    }
}

Thread thread=new Thread(new ThreadRunableDemo());
thread.start();

//可以采用匿名对象的方式就不用再创建类了
Thread thread2=new Thread(new Runnable() {
    public void run() {
        System.out.println("匿名对象形式");
    }
});
thread2.start();

3、通过实现Callable接口+Future

public class ThreadCallable implements Callable<String> {

    public String call() throws Exception {
        return "aaaa";
    }
}

Callable<String> callable = new ThreadCallable();
FutureTask<String>futureTask=new FutureTask<String>(callable);
//会阻塞线程
futureTask.get();

关于Runable和Callable的区别

https://blog.csdn.net/heyutao007/article/details/19072675

java中线程池

ExecutorService es = Executors.newFixedThreadPool(2);

es.submit(new Runnable() {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
});
es.submit(new Runnable() {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
});

线程安全

synchronized 同步

# 同步代码块
 synchronized (obj) {}

# 同步方法
public synchronized void DT() {}

锁(jdk1.5后)

private Lock lock = new ReentrantLock();
lock.lock();
do something.......
lock.unlock();


https://www.cnblogs.com/CarpenterLee/p/9558026.html


posted @ 2018-06-23 07:58  迁梦余光  阅读(158)  评论(0编辑  收藏  举报