Java并发编程原理(一)

创建线程的多种方式

  1. 继承Thread类
package com.yrz;

/**
         * @author yrz
         * @site www.yrz.com
         * @create 2019-01-13 10:51
         */

public class ExtendsThread extends Thread {
public ExtendsThread(String name) {
super(name);
}

         @Override
public void run() {
while (!interrupted()) {
                        System.out.println(getName() + "线程执行了 .. ");
try {
                            Thread.sleep(200);
} catch (InterruptedException e) {
                            e.printStackTrace();
}
}
}



public static void main(String[] args) {
    	 ExtendsThread d1 = new ExtendsThread("first-thread");
        ExtendsThread d2 = new ExtendsThread("second-thread");

        d1.start();
        d2.start();
        d1.interrupt();  }}
  1. 实现Runnable接口
package com.yrz;

/**
 * 创建线程的方法  实现runnable
 * @author yrz
 * @site www.yrz.com
 * @create 2019-01-08 23:29
 */
public class ImpRunnable implements Runnable{
@Override
public void run() {
while (true)
            System.out.println("thread start");
}

public static void main(String args[]){
        Thread t = new Thread(new ImpRunnable());
        t.start();
}
}

  1. 匿名内部类的方式
package com.yrz;

/**
* 创建线程的方式--匿名内部类
* @author yrz
* @site www.yrz.com
* @create 2019-01-08 23:39
 */
public class innerThread {
public  static void main(String args[]){
new Thread(new Runnable() {
@Override
public void run() {
                System.out.println("匿名内部类的方式实现线程");
}
}).start();
}
}

  1. 带返回值的线程
package com.yrz;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author yrz
 * @site www.yrz.com

 * @create 2019-01-08 23:43
 */
public class ReturnThread implements Callable {

public static void main(String args[]){
        ReturnThread run = new ReturnThread();
        FutureTask<String> future =new FutureTask<>(run);
                Thread t=new Thread(future);
        t.start();
        String res = null;
try {
            res = future.get();
} catch (InterruptedException e) {
            e.printStackTrace();
} catch (ExecutionException e) {
            e.printStackTrace();
}

        System.out.println("------"+res);
}
@Override
public String call() throws Exception {

return "带有返回值的线程创建";
}
}

  1. 定时器(quartz)
package com.yrz;

import java.util.Timer;
import java.util.TimerTask;

/**
* @author yrz
* @ClassName quartzThread
* @site www.yrz.com
* @create 2019-01-13 18:44
* @Version 1.0
*/
public class QuartzThread extends TimerTask {

@Override
public void run() {
        System.out.println("timertask is run");
}


public static void main(String args[]) {

        Timer timer = new Timer();
        QuartzThread quartzThread = new QuartzThread();
        quartzThread.run();
        timer.schedule(quartzThread, 0, 1000);


}
}

  1. 线程池的实现
package com.yrz;

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

/**
 * @author yrz
 * @ClassName Executor
 * @site www.yrz.com
 * @create 2019-01-13 18:58
 * @Version 1.0
 */
public class Executor {
/**
* corePoolSize,线程池里最小线程数
* maximumPoolSize,线程池里最大线程数量,超过最大线程时候会使用RejectedExecutionHandler
* keepAliveTime,unit,线程最大的存活时间
* workerQueue,缓存异步任务的队列
* threadFactory,用来构造线程池里的worker线程
* @param args
     */
public static void main(String args[]) {
//CachedThreadPool创建和任务数量相同的线程数
//创建一个可缓存线程池,应用中存在的线程数可以无限大
        ExecutorService CacExecutorService = Executors.newCachedThreadPool();

for (int i = 0; i < 5; i++) {
            CacExecutorService.execute(new Runnable() {
@Override
public void run() {
                    System.out.println(Thread.currentThread().getName());
}
});
}
 运行结果

pool-1-thread-1
pool-1-thread-5
pool-1-thread-2
pool-1-thread-4
pool-1-thread-3
//只能创建一个线程      
//创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行        
   ExecutorService SigExecutorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
    SigExecutorService.execute(new Runnable() {
@Override
public void run() {
            System.out.println(Thread.currentThread().getName());
}
});
}

运行结果
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1


//指定创建的线程数
//创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
        ExecutorService fixExecutorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
            fixExecutorService.execute(new Runnable() {
@Override
public void run() {
                    System.out.println(Thread.currentThread().getName());
}
});

}

}
}
 运行结果
 pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-1
pool-1-thread-3
  1. Lambda表达式实现
 	package com.yrz;

import java.util.Arrays;
import java.util.List;

/**
* @author yrz
* @ClassName Lambda
* @site www.yrz.com
* @create 2019-01-13 19:40
* @Version 1.0
*/
public class Lambda {
    public static void main(String args[]) {
        List<Integer> list = Arrays.asList(10, 30, 40, 20);
        System.out.println("计算结果" + new Lambda().add(list));
    }

    public int add(List<Integer> values) {
        //   values.parallelStream().forEach(System.out :: println);
        // return   values.stream().mapToInt(i->i).sum();
        //求和
        return values.parallelStream().mapToInt(i -> i).sum();
    }

}
运行结果
计算结果100
  1. Spring实现多线程
  • ThreadConfig 实现AsyncConfigurer 异步接口,创建线程池
  • AsynTaskService 具体要创建异步任务
  • 创建main函数测试
package com.yrz;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author yrz
 * @site www.yrz.com
 * @create 2019-01-12 23:41
 */
@Configuration
@ComponentScan("com.yrz")
@EnableAsync//启动异步任务
public class ThreadConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);//可异步开启的线程数
        executor.setMaxPoolSize(10);//最大线程数
        executor.setQueueCapacity(25);//每个线程可排队数
        executor.initialize();
return executor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}

package com.yrz;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;

/**
 * @author yrz
 * @site www.yrz.com
 * @create 2019-01-12 23:46
 */
@Service//将AsynTaskService交给spring管理
public class AsynTaskService {
// 这里可以注入spring中管理的其他bean,这也是使用spring来实现多线程的一大优势
@Async    // 这里进行标注为异步任务,在执行此方法的时候,会单独开启线程来执行
public void f1() {
        System.out.println("f1 : " + Thread.currentThread().getName() + "   " + UUID.randomUUID().toString());
try {
            Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
            e.printStackTrace();
}
}

@Async
public void f2() {
        System.out.println("f2 : " + Thread.currentThread().getName() + "   " + UUID.randomUUID().toString());
try {
            Thread.sleep(100);
} catch (InterruptedException e) {
            e.printStackTrace();
}
}

}

import com.yrz.AsynTaskService;
import com.yrz.ThreadConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author yrz
 * @site www.yrz.com
 * @create 2019-01-12 23:01
 */
public class Main {
public static void main(String agrs[]) {
//创建AnnotationConfigApplicationContext 将ThreadConfig放入spring容器管理
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ThreadConfig.class);

        AsynTaskService service = context.getBean(AsynTaskService.class);

for (int i = 0; i < 10; i++) {
            service.f1();
            service.f2();
}

        context.close();
}
}



运行结果:

ThreadPoolTaskExecutor-1   bd535a93-4fdd-4e50-b027-9182dea4ff5a f1 
ThreadPoolTaskExecutor-5   f118ed63-2dee-493a-9326-e2d4b71c5c11 f2 
ThreadPoolTaskExecutor-2   c9c1d664-e6d1-4d93-8a56-67dbeba823cb f2  
ThreadPoolTaskExecutor-4   fefba07d-4361-4f06-b844-28210c087322 f1 
ThreadPoolTaskExecutor-3   e90d7e28-bfbf-4588-b3b9-8cc41ae5cb74 f2 
ThreadPoolTaskExecutor-3   c98dbd8c-b948-4aa3-9635-9fd552853533 f1  
ThreadPoolTaskExecutor-1   62f06e34-1ae5-4aba-bacb-0bf2872f051e f2 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值