多线程自总结

1.Thread, Runnable, Callable开启线程

  1. Thread 方法继承Thread,并重写run();
 class SomeThead extends Thraad   { 
    public void run()   { 
     //do something here  
    }  
 } 
 
public static void main(String[] args){
 SomeThread oneThread = new SomeThread();   
  步骤3:启动线程:   
 oneThread.start(); 
}

2.实现Runnable接口创建线程

class SomeRunnable implements Runnable   { 
  public void run()   { 
  //do something here  
  }  
} 
Runnable oneRunnable = new SomeRunnable();   
Thread oneThread = new Thread(oneRunnable);   
oneThread.start(); 

3.Callable 和 Future 创建线程

public interface Callable   { 
  V call() throws Exception;  
 } 
  步骤1:创建实现Callable接口的类SomeCallable(略);   
  步骤2:创建一个类对象: 
      Callable oneCallable = new SomeCallable(); 
  步骤3:由Callable创建一个FutureTask对象:   
    FutureTask oneTask = new FutureTask(oneCallable); 
  注释: FutureTask是一个包装器,它通过接受Callable来创建,它同时实现了 Future和Runnable接口。 
  步骤4:由FutureTask创建一个Thread对象:   
    Thread oneThread = new Thread(oneTask);   
  步骤5:启动线程:  
    oneThread.start(); 

2.线程的生命周期

1.新建状态,就绪状态,运行状态,阻塞状态,死亡状态
2.函数:sleep():当前运行的线程休眠,而不是当前线程休眠
wait():等待
notify():通知一个线程
notifyAll():通知所有线程
yeild():让出进程,重新进入就绪
join():让几个并行的线程组合成串行的线程
setPriority(int newPriority)和getPriority() :设置优先级
3.结束线程:不应该使用stop(),suspend(),resume()等。
正确的方法是使用标识符来结束掉线程

class MyThread extends Thread {  
    int i=0;  
    boolean next=true;  
    @Override  
    public void run() {  
        while (next) {  
            if(i==10)  
                next=false;  
            i++;  
            System.out.println(i);  
        }  
    }  
}

3.线程同步

1.synchronized关键字
synchronize修饰的方法和 synchronize(this) 都是锁住自己本身的对象 而synchronize(class) synchronize(object) 都是锁别的对象

2.特殊域变量volatile
有锁保护的域和volatile域可以避免非同步的问题。

3.重入锁 ReentrantLock(),lock(),unlock()

   class Bank {
        
        private int account = 100;
        //需要声明这个锁
        private Lock lock = new ReentrantLock();
        public int getAccount() {
            return account;
        }
        //这里不再需要synchronized 
        public void save(int money) {
            lock.lock();
            try{
                account += money;
            }finally{
                lock.unlock();
            } 
        }
    } 

4.使用阻塞队列控制线程通信 (BlockingQueue)

4.线程池

1.ExecutorService :Java中对线程池定义的一个接口,最常用的线程池ThreadPoolExecutor

  1. 调用Executors类的静态工厂方法创建一个ExecutorService对象,该对象代表一个线程池;
  2. 创建Runnable实现类或Callable实现类的实例,作为线程执行任务;
  3. 调用ExecutorService对象的submit()方法来提交Runnable实例或Callable实例;
  4. 当不想提交任务时,调用ExecutorService对象的shutdown()方法来关闭线程池。

2.线程池种类:newFixedThreadPool() ,newCachedThreadPool() ,newSingleThreadExecutor() ,newScheduledThreadPool() ,newSingleThreadScheduledExecutor()

3.ExecutorService 方法函数:
**- execute(Runnable):**方法接收一个Runnable实例
**- submit(Runnable):**返回一个Future对象,通过Future对象,我们可以检查提交的任务是否执行完毕

- Future future = executorService.submit(new Runnable() {
public void run() {
    System.out.println("Asynchronous task");
}
});
future.get();  //returns null if the task has finished correctly.
  • **submit(Callable):**Callable线程返回future对象
    **- invokeAny(…):**接收的是一个Callable的集合,无法保证返回的是哪个任务的执行结果,反正是其中的某一个
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
public String call() throws Exception {
    return "Task 1";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
    return "Task 2";
}
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
    return "Task 3";
}
});
String result = executorService.invokeAny(callables);
System.out.println("result = " + result);
executorService.shutdown();

**- invokeAll(…):**接收一个Callable集合,但是前者执行之后会返回一个Future的List,其中对应着每个Callable任务执行后的Future对象。

 ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
public String call() throws Exception {
    return "Task 1";
}
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
    return "Task 2";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
    return "Task 3";
}
});
List<Future<String>> futures = executorService.invokeAll(callables);
for(Future<String> future : futures){
    System.out.println("future.get = " + future.get());
}
executorService.shutdown();

4.ExecutorService关闭方法:ExecutorService.shutdown()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值