6、多线程

线程创建方法1:继承Thread类

1、自定义线程类,继承(extends)Thread
2、重写run()方法
3、创建线程对象,调用start()方法启动线程

线程创建方法2:实现Runnable类(常用,因为接口可以多继承)

1、自定义线程类RunnableTest,实现(implements)Runnable类
2、重写run()方法
3、创建线程对象p,new Thread(p,“线程名称”).start()方法启动线程(线程名称可省略,主要用于区分多个相同对象)

RunnableTest p=new RunnableTest();	
Thread thread = new Thread(p);	
thread.start;
1、线程休眠:thread.sleep();
2、线程礼让(停止当前线程,重新让CPU调度):thread.yield();
3、线程插队(强制优先执行p这个线程):thread.join();
4、线程状态获取:thread.getState();
5、获取线程名称:thread.currentThread.getName();
6、获取线程优先级(设置用set,1-10之间,先设置再启动,优先级是占比相对大,不是绝对优先):thread.getPriority();
7、守护线程(默认位false,即用户线程,设为true时,是守护线程,守护其他线程结束便结束) :thread.setDaemon(true);
8、同步监视器,隐式锁,synchronized(Ojb){增删改方法}。
        ArrayList<String>arrayList=new ArrayList<String>();
        //JUC安全类型的集合CopyOnWriteArrayList
        CopyOnWriteArrayList<String> copyOnWriteArrayList=new CopyOnWriteArrayList<String>();
        for (int i = 0; i < 30000; i++) {
            new Thread(()->{
                //ArrayList,线程不安全,实际size不到100000个
                //arrayList.add(Thread.currentThread().getName());
                copyOnWriteArrayList.add(Thread.currentThread().getName());
                //同步监视器,synchronized(Ojb){增删改方法}。size正常=100000
                synchronized (arrayList){
                    arrayList.add(Thread.currentThread().getName());
                }
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("arrayList.size()="+arrayList.size());
        System.out.println("copyOnWriteArrayList.size()="+copyOnWriteArrayList.size());
9、显式锁,ReentrantLock,手动开启关闭锁。
        //main里调用       
        Ticket ticket=new Ticket();
        new Thread(ticket).start();
        new Thread(ticket).start();
        new Thread(ticket).start();


static class Ticket implements Runnable{
        private int TicketNum=100;
        private final ReentrantLock lock=new ReentrantLock();

        @Override
        public void run() {
            while (true){
                try {
                    lock.lock();//开锁
                    if(TicketNum>0){
                        Thread.sleep(100);
                        System.out.println(TicketNum--);
                    }
                    else {
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();//关锁
                }


            }
        }
    }
10、管程法,生产者/消费者模式,消费者不直接拿生产者的数据,而是从缓冲区拿数据
public static void main(String[] args) {
        //管程法
        Buffer buffer=new Buffer();
        new Thread(new Producer(buffer)).start();
        new Thread(new Consumer(buffer)).start();
    }
    //生产者
    static class Producer implements Runnable{
        Buffer buffer;

        public Producer(Buffer buffer) {
            this.buffer = buffer;
        }

        @Override
        public void run() {
            for (int i = 1; i < 100; i++) {
                System.out.println("生产了第"+i+"个产品");
                buffer.add(new Product());
            }
        }
    }

    //消费者
    static class Consumer implements Runnable{
        Buffer buffer;

        public Consumer(Buffer buffer) {
            this.buffer = buffer;
        }

        @Override
        public void run() {
            for (int i = 1; i < 100; i++) {
                System.out.println("  消费者消费了   第"+i+"个产品");
                buffer.reduce();
            }
        }
    }

    //产品
    static class Product{
        int id;
    }

    //缓冲区
    static class Buffer {
        Product[]products=new Product[10];
        int count =0;
        //生产这进行新增
        public synchronized void add(Product product){
            if(count==products.length){
                //缓冲区满了,等待减少
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            products[count]=product;
            count++;
            System.out.println("      缓存区有"+count+"个产品");
            this.notifyAll();
        }

        //消费者进行减少
        public synchronized void reduce(){
            if(count==0){
                //缓冲区空了,等待新增
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count--;
            System.out.println("      缓存区有"+count+"个产品");
            this.notifyAll();
        }
    }
10、信号灯法,生产者/消费者模式,根据一个变量去确定是等待,还是执行
public class ThreadTest3 {
    public static void main(String[] args) {
        TV tv=new TV();
        new Thread(new Seeer(tv)).start();
    }

}
//表演者
class Player implements Runnable{
    private TV tv;
    private String project;
    public Player(TV tv,String project) {
        this.tv = tv;
        this.project = project;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            tv.play(project);
            if(i%2==0){
                tv.play("吉祥如意的一家");
            }
            else{
                tv.play(project);
            }
        }
    }
}
//观看者
class Seeer implements Runnable{
    private TV tv;
    public Seeer(TV tv) {
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.see();
        }
    }
}

class TV {
    private String project;
    private boolean flag=true;
    synchronized void play(String project){
        if(flag==true){
            System.out.println("表演者表演了<"+project+">");

            //Thread.currentThread().notifyAll();//这里只能用this,用这个会报错
            this.flag=false;
            this.project=project;
            this.notifyAll();
        }
        else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    synchronized void see(){
        if(flag==false){
            System.out.println("    观看者看了  "+project);
            this.flag=true;
            this.notifyAll();
        }
        else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
11、线程池
public class ThreadTest3 {
    public static void main(String[] args) {
        ExecutorService service= Executors.newFixedThreadPool(10);//参数:线程池的大小
        service.execute(new TestThread());
        service.execute(new TestThread());
        service.execute(new TestThread());
    }
}

class TestThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值