Java-多线程2

高级并发对象

线程定义:实现Callable接口
实现Runnable接口与继承Thread类两种线程定义方式都有这两个问题:

  1. 无法获取子线程的返回值;
  2. run方法不可以抛出异常。
    为了解决这两个问题,我们就需要用到Callable这个接口了。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class HelloCallable implements Callable {
    int i = 0;
    @Override
    public Object call() throws Exception {
        for (int i1 = 0; i1 < 10; i1++) {
            System.out.println(Thread.currentThread().getName() + ": " + i++);
        }
        return i;
    }
    public static void main(String[] args) {
        HelloCallable helloCallable = new HelloCallable();
        for (int i = 0; i < 10; i++) {
            FutureTask futureTask = new FutureTask(helloCallable);
            Thread thread = new Thread(futureTask, "子线程" + i);
            thread.start();
            try {
                System.out.println("子线程" + i + "返回值: " + futureTask.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

线程同步:锁对象
同步代码依赖于一种简单的可重入锁。这种锁易于使用,但有很多限制。 java.util.concurrent.locks软件包支持更复杂的锁定习惯用法 。
Lock对象的工作方式非常类似于同步代码所使用的隐式锁。与隐式锁一样,一次只能有一个线程拥有一个Lock对象。 Lock对象还wait/notify通过其关联的Condition对象支持一种机制 。

import java.util.concurrent.locks.ReentrantLock;
public class ThreadLock implements Runnable {
public static int ticket = 100;
ReentrantLock reentrantLock = new ReentrantLock();
@Override
public void run() {
while (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
reentrantLock.lock();
if (ticket <= 0) {
return;
}
System.out.println(Thread.currentThread().getName() + "卖了1张票,剩余" + --ticket + "张票");
reentrantLock.unlock();
}
}
public static void main(String[] args) {
ThreadLock threadLock = new ThreadLock();
Thread thread1 = new Thread(threadLock, "售票员1");
thread1.start();
Thread thread2 = new Thread(threadLock, "售票员2");
thread2.start();
Thread thread3 = new Thread(threadLock, "售票员3");
thread3.start();
}
}

线程池
Java中创建和销毁一个线程是比较昂贵的操作,需要系统调用。频繁创建和销毁线程会影响系统性能。
使用线程池带来以下好处:

  1. 降低资源的消耗。线程本身是一种资源,创建和销毁线程会有CPU
    开销;创建的线程也会占用一定的内存。
  2. 提高任务执行的响应速度。任务执行时,可以不必等到线程创建完
    之后再执行。
  3. 提高线程的可管理性。线程不能无限制地创建,需要进行统一的分
    配、调优和监控。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new ThreadPool());
executorService.execute(new ThreadPool());
executorService.execute(new ThreadPool());
executorService.shutdown();
}
}

并发集合: BlockingQueue
BlockingQueue实现被设计为主要用于生产者-消费者队列,如果BlockingQueue是空的,从BlockingQueue取东西的操作将会被阻断进入等待状态,直到BlockingQueue进了东西才会被唤醒。同样,如果BlockingQueue是满的,任何试图往里存东西的操作也会被阻断进入等待状态,直到BlockingQueue里有空间时才会被唤醒。BlockingQueue实现是线程安全的。所有排队方法都可以使用内部锁或其他形式的并发控制来原子地实现其效果

public class Product {
private String name;
public Product(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/*===================================================*/
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
BlockingQueue<Product> blockingQueue;
public Producer(BlockingQueue<Product> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
int i = 0;
while (true) {
try {
Product product = new Product("" + i++);
blockingQueue.put(product);
System.out.println("生产产品: " + product.getName());
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/*===================================================*/
import java.util.concurrent.*;
public class MainMethod {
public static void main(String[] args) {
BlockingQueue<Product> BlockingQueue = new
ArrayBlockingQueue<Product>(100);
Producer producer = new Producer(BlockingQueue);
Consumer consumer = new Consumer(BlockingQueue);
new Thread(producer).start();
new Thread(consumer).start();
}
}

静态代理
静态代理就是在编译时就确定了代理类与被代理类的关系。

public class StaticProxy {
public static void main(String[] args) {
Me me = new Me();
WeddingCompany weddingCompany = new
WeddingCompany(me);
weddingCompany.marryMethod();
}
}
interface Marry {
void marryMethod();
}
class Me implements Marry {
@Override
public void marryMethod() {
System.out.println("哈哈,我要结婚了!!! ");
}
}
class WeddingCompany implements Marry {
private Marry marrry;
public WeddingCompany(Marry marrry) {
this.marrry = marrry;
}
@Override
public void marryMethod() {
before();
this.marrry.marryMethod();
after();
}
public void before() {
System.out.println("结婚之前,布置现场。 ");
}
public void after() {
System.out.println("结婚之后,收取费用。 ");
}
}

Lamda表达式
Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
使用 Lambda 表达式可以使代码变的更加简洁紧凑。


public class LambdaExpression {

    /**
     * 2、静态内部类
     */
    static class Love2 implements ILove {
        @Override
        public void lambda() {
            System.out.println("I Love Lambda 2");
        }
    }

    public static void main(String[] args) {
        // 1、外部类
        Love1 love1 = new Love1();
        love1.lambda();

        // 2、静态内部类
        Love2 love2 = new Love2();
        love2.lambda();

        /**
         * 3、局部内部类
         */
        class Love3 implements ILove {
            @Override
            public void lambda() {
                System.out.println("I Love Lambda 3");
            }
        }

        // 3、局部内部类
        Love3 love3 = new Love3();
        love3.lambda();


        /**
         * 4、匿名类
         */
        ILove love4 = new ILove() {
            @Override
            public void lambda() {
                System.out.println("I Love Lambda 4");
            }
        };

        // 4、局部内部类
        love4.lambda();

        /**
         * 5、Lambda表达式
         */
        ILove love5 = () -> {
            System.out.println("I Love Lambda 5");
        };

        // 5、Lambda表达式
        love5.lambda();

    }
}

/**
 * 接口
 */
interface ILove {
    void lambda();
}

/**
 * 1、外部类
 */
class Love1 implements ILove {
    @Override
    public void lambda() {
        System.out.println("I Love Lambda 1");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值