java基础性代码拾遗-4(多线程)

1. 进程和线程的区别
区别进程线程
根本区别作为资源分配的单位调度执行的单位
开销每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有较大的开销。切换发生在不同的内存地址上。轻量级进程,同一类线程共享代码和数据空间,每个线程有独立的运行栈,以及程序计数器。线程的切换开销小。切换发生在同一内存地址上。
内存分配每个进程分配不同的内存区域。不会为线程分配内存。线程使用的资源是它所属的进程的。线程组只能共享资源
2. 静态代理模式
  • Thread:代理角色
  • 实现Runnable接口的类:真实角色
  • 有代理就有机会在执行真实角色对象方法之前或之后加入额外的动作。
3. 常用方法
Thread t=Thread.currentThread() //获取当前线程对象
Thread.currentThread().toString() //输出当前线程对象的[name,priority,group]
t.getName() //获取线程的名称
t.setName() //修改线程的名称
Thread t=new Thread(MyRunnable,"自定义线程名称")
4. 线程控制方法
t.join() 让线程t插队
Thread.yield() 礼让,让出CPU的使用权一次(从运行态进入就绪态)
Thread.sleep() 暂停,占用CPU,不释放锁
5. 同步锁
  • 同步代码块
synchronized(obj){
	...
}

obj为同步对象(只能是对象),且一般选择为共享资源的对象。可以是this当前对象,也可以是其他对象。

  • 同步方法
public synchronized ... methodName(args...){
	...
}

同步方法的同步对象为this。

6. 使用Callable接口启动线程

使用继承Thread或者使用Runnable接口静态代理的方式,存在如下缺点:

  • 没有返回值
  • 不支持泛型
  • 异常必须处理,不能外抛throws。

为此可以实现Callable接口,重写call()方法。

public class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        String[] gentleman={"春申君","信陵君","平原君","孟尝君"};
        int index=(int) (Math.random()*3);
        return gentleman[index];
    }
}

class Test{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable call=new MyCallable();
        FutureTask<String> task=new FutureTask<>(call);
        Thread t=new Thread(task);
        t.start();
        //获取返回值
        System.out.println("春秋四公子:"+task.get());
        //判断是否执行完成
        System.out.println("任务是否执行完成:"+task.isDone());
    }
}
7. 线程同步锁Lock

监控实现Lock接口的类。
java.util.concurrent.lock中的Lock是一个接口,它的实现类是一个Java类,而不是关键字。在线程同步中比synchronized更灵活。如果同步代码有异常,要将unLock()放到finally中。

public class CountRunnable implements Runnable {
    private int count = 0;

    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            //synchronized (this) {
            try {
                lock.lock();
                count++;
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行操作:count=" + count);
            } finally {
                lock.unlock();
            }
        }
    }
}

class Test {
    public static void main(String[] args) {
        CountRunnable cr = new CountRunnable();
        Thread t1 = new Thread(cr, "A");
        Thread t2 = new Thread(cr, "B");
        Thread t3 = new Thread(cr, "C");

        t1.start();
        t2.start();
        t3.start();
    }
}

Lock与synchronized的区别

  • Lock是显式锁,需要手动开启和关闭,而隐式锁synchronized不需要。
  • Lock只有代码块锁,而synchronized有代码块锁和方法锁。
  • 使用Lock锁JVM将花费更少的时间来调度线程。有更好的性能和扩展性(提供更多的子类)。
  • Lock本质是一个临界区锁。
8. 线程池
  • 执行Runnable任务
public class Test1 {
    public static void main(String[] args) {
        //线程池中只有一个线程
//        ExecutorService pool1 = Executors.newSingleThreadExecutor();
        //线程池中有固定数量的线程
        ExecutorService pool1 = Executors.newFixedThreadPool(10);
        //线程池中的线程数是动态改变的(按需)
//        ExecutorService pool1 = Executors.newCachedThreadPool();
		//执行大量任务
        for (int i = 0; i < 20; i++) {
            final int n = i;
            Runnable cmd = new Runnable() {
                @Override
                public void run() {
                    System.out.println("开始执行:" + n);
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("执行结束:" + n);
                }
            };
            pool1.execute(cmd);
        }
        pool1.shutdown();
    }
}
  • 执行Callable任务
public class Test2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //线程池中只有一个线程
//        ExecutorService pool1 = Executors.newSingleThreadExecutor();
        //线程池中有固定数量的线程
        ExecutorService pool1 = Executors.newFixedThreadPool(10);
        //线程池中的线程数是动态改变的(按需)
//        ExecutorService pool1 = Executors.newCachedThreadPool();

        List<Future> list = new ArrayList<>();

        //执行大量任务
        for (int i = 0; i < 20; i++) {
            final int n = i;
            Callable<Integer> task = new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(500);
                    return (int) (Math.random() * 10) + 1;
                }
            };
            Future f = pool1.submit(task);
            list.add(f); //先把任务都分发出去
//            System.out.println(f.get()); //要等到每个线程执行结束才得到返回值,效率较低
        }
        System.out.println("分发异步执行");
        for (Future f : list) { //最后再收集返回结果
            System.out.println(f.get());
        }
        System.out.println("获得最终执行结果");
        pool1.shutdown();
    }
}
9. ThreadLocal在数据库连接上的应用

ThreadLocal经常应用在数据库连接和session管理上。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值