Java中并发编程基础

Java中并发编程基础

  • 编写程序,覆盖Callable的call()方法,定义两个任务,一个任务求前10个斐波那契之和
  • 第二个任务求前10个素数之和,将者这两个子任务提交给ExecutorService执行,
  • 通过返回Future的get()方法输出两个子任务的结果

import java.util.concurrent.*;

public class CallableDemo {
    public static long fibonacci(int n){ //求斐波那契数列第n项的方法
        if(n == 1 || n == 2){
            return 1  ;
        }
        else{
            return fibonacci(n-1) + fibonacci(n-2) ;
        }
    }
    public static boolean isPrime(int n){ //判断是否是素数的方法
        if(n == 2){
            return true ;
        }
        for(int i=2; i<n; i++){
            if(n % i == 0){
                return false ;
            }
        }
        return true ;
    }
    public static void main(String[] args){
        Callable<Long> task1 = new Callable<Long>() { //创建任务对象,重写call()方法,并抛出异常
            @Override
            public Long call() throws Exception {
                int count = 1 ;
                long sum = 0 ;
                while(count <= 10){
                    sum += fibonacci(count) ;
                    count ++ ;
                }
                return sum ;
            }
        };
        Callable <Long> task2 = new Callable<Long>() { //创建线程任务,重写call()方法并抛储异常
            @Override
            public Long call() throws Exception {
                int count = 1 ;
                long sum = 0;
                int value = 2 ;
                while(count <= 10){
                    if(isPrime(value)){
                        sum += value ;
                        count ++ ;
                    }
                    value ++ ;
                }
                return sum;
            }
        };
        ExecutorService executor = Executors.newCachedThreadPool() ; //创建线程执行器对象
        Future <Long> result1 = executor.submit(task1) ; //提交线程任务给执行器
        Future <Long> result2 = executor.submit(task2) ;
        try{ //处理抛出的异常
            System.out.println(result1.get()) ; //获取执行器中的结果
            System.out.println(result2.get()) ;
        }catch(InterruptedException | ExecutionException e){
            System.out.println(e.getMessage()) ;
        }

    }
}

  • 使用Runnable接口实现构造线程任务,不重写run()方法,而直接使用Runnable接口和lambda表达式实现

public class RunnableDemo {
    public static void main(String[] args){
        Runnable task = () -> { //创建线程任务
            for(int i=0; i<100; i++){
                System.out.println(Thread.currentThread().getName() + ":" + i) ;
                try{
                    Thread.sleep((int) Math.random() * 100) ;
                }catch(InterruptedException e){
                    System.out.println(e.getMessage()) ;
                }
            }
        } ;
        Thread thread1 = new Thread(task, "线程A") ; //使用线程名称和线程任务创建线程对象
        Thread thread2 = new Thread(task, "线程B") ;
        thread1.start() ; //启动线程
        thread2.start() ;
    }
}

  • Account类表示账户,初始余额为1000元,定义线程类模拟从账户取钱,规定每个线程每次只取出100元
  • 创建两个线程,从账户取钱
public class Account {
    private int balance = 1000 ; //初始余额
    public void deposit(int amount){ //存款方法
        balance += amount ;
    }
    public void withdraw(int amount){ //取款方法
        balance -= amount ;
    }
    public int getBalance(){
        return balance ;
    }
}
public class AccountSafe implements Runnable{ //实现Runnable接口并重写run()方法
                Account account = new Account() ; //实例化账户对象
                public synchronized void makeWithdraw(int amount){ //取款的同步方法
                    if(account.getBalance() >= amount){ //判断余额是否够
                        account.withdraw(100) ;
                        System.out.println(Thread.currentThread().getName() + "取款:" + amount + "账户余额:" + account.getBalance()) ;
                        try{
                Thread.sleep(100) ;
            }catch(InterruptedException e){
                System.out.println(e.getMessage()) ;
            }
        }
        else{
            System.out.println("账户余额不足" + Thread.currentThread().getName() + "余额为:" + account.getBalance()) ;
        }
    }
    @Override
    public void run() { //创建线程任务对象
        for(int i=0; i<15; i++){
            makeWithdraw(100) ;
            if(account.getBalance() <= 0){
                System.out.println("账户透支!!!") ;
            }
        }
    }
    public static void main(String[] args){
        AccountSafe task = new AccountSafe() ; //实例化线程任务
        Thread thread1 = new Thread(task,"王国栋") ; //以线程名和任务对象创建线程对象
        Thread thread2 = new Thread(task,"唐乃乔") ;
        thread1.start() ;//启动线程
        thread2.start() ;
    }
}

你可能感兴趣的:(JavaSE,java,多线程,并发编程,thread)