QtAnt Design Pro

多线程和Lambda表达式

2018-07-22  本文已影响755人  须臾之北

7月20日知识点

今天的主要内容——线程

线程

1. 线程的基本概念

注:

① Java的线程是通过java.lang.Thread类来实现的

② VM启动时会有一个主方法(main方法)所定义的线程

③ 可通过创建Thread的实例来创建新的线程

④ 每个线程都是通过某个特定的Thread对象所对应的run方法来完成其操作的,方法run()称为线程体

⑤ 通过调用Thread类中的start()方法来启动一个线程。

2. 多线程(多线程并行和并发的区别)(了解)

3. 多线程(Java程序运行原理和JVM的启动是多线程的吗)(了解)

4. 线程的两种创建方式

image image image image

3. 线程两种创建方式程序

* 能使用接口实现线程就不要用继承,因为用了接口以后还可以继承和实现其它接口,而如果只继承会比较死板

4. 创建线程的两种方式的区别(掌握)

            public void run() {
                if (target != null) {
                    target.run();
                }
            }

5. 匿名内部类实现线程

6. 创建线程的两种方式的区别(掌握)

* 弊端是:如果已经有了父类,就不能用这种方法
* 弊端是:不能直接使用Thread中的方法需要先获取到线程对象后,才能得到Thread的方法,代码复杂

7. 线程的第三种创建方式

7.1 FutureTask类的学习——java.util.concurrent.FutureTask<V>
image image

8. 多线程(获取名字和设置名字)(掌握)

9. 多线程(获取当前线程的对象)(掌握)

public static Thread currentThread()

Thread.currentthread();——注意返回值是Thread

//匿名内部类实现当前线程对象的获取
new Thread() {          
    public void run() {
        this.setName("线程A");
        
        for(int i = 0;i < 1000;i++) {
            System.out.println( Thread.currentThread().getName() + "....aaaa");
        }
    }
    
}.start();

new Thread(new Runnable() {
    public void run() {
        for(int i = 0;i < 1000;i++) {
            System.out.println( Thread.currentThread().getName() + "....bb");
        }
    }
},"线程B").start();       

}

10. 多线程(休眠线程)(掌握)

        public class TestSleepOfThread {
            public static void main(String[] args) {
                
                Runnable r = ()->{
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                    System.out.println("Thread A");
                };
                
                new Thread(r).start();
                
                System.out.println("main Thread");
            }
        }
        /*
         * 在JDK1.8中输出结果为:
         * -------------
         * main Thread
           Thread A
           -------------
         * */

11. 多线程(守护线程)(掌握)

12. 多线程(加入线程)(掌握)

13. 多线程(礼让线程)(了解)

14. 多线程(设置线程的优先级)(了解)

15. 多线程(同步代码块)(掌握)

16. 多线程(同步方法)(掌握)

public class TestSynchronized_2 {
    
    public static void main(String[] args) {
        Printer_2 p = new Printer_2();
        
        Runnable r = ()->{
            for(int i = 0;i < 100;i++) {
                p.print1();
            }
        };
        
        Thread t2 = new Thread() {
            public void run() {
                for(int i = 0;i < 100;i++) {
                    p.print2();
                }
            }
        };
        
        new Thread(r).start();
        t2.start();     
    }
}

class Printer_2{
    public synchronized void print1() {
        System.out.print("早");
        System.out.print("上");
        System.out.print("好");
        System.out.print("啊");
        System.out.print("\r\n");
    }
    
    public void print2() {
        synchronized(this) {
            System.out.print("河");
            System.out.print("正");
            System.out.print("宇");
            System.out.print("好");
            System.out.print("帅");  
            System.out.print("\r\n");
        }       
    }   
}

17. 多线程(线程安全问题)(掌握)

18. 多线程(火车站卖票的例子用实现Runnable接口)(掌握)

public class TestSynchronized_4 {
    public static void main(String[] args) {
        Ticket_2 t = new Ticket_2();
        
        new Thread(t,"线程A").start();
        new Thread(t,"线程B").start();
        new Thread(t,"线程C").start();
        new Thread(t,"线程D").start();
    }
}

class Ticket_2 implements Runnable{
    private int ticket = 100;  //此时ticket不需要设置为共享,因为均为同一对象
    
    @Override
    public void run() {
        while(true) {
            synchronized(this) {
                if(ticket == 0) {
                    break;
                }
                
                System.out.println(Thread.currentThread().getName() + " 这是第" + ticket-- + "号票");
            }
        }
    }
}

19. 多线程(死锁)(了解)

public class TestDeadLock {
    private static Object o1 = new Object();
    private static Object o2 = new Object();
    
    
    public static void main(String[] args) {
        new Thread("线程A") {
            public void run() {
                while(true) {
                    synchronized(o1) {
                        System.out.println(getName() + "正在使用o1,等待o2");
                        synchronized(o2) {
                            System.out.println(getName()  +"等到o2,执行成功");
                        }
                    }
                }               
            }
        }.start();
        
        new Thread("线程B") {
            public void run() {
                while(true) {
                    synchronized(o2) {
                        System.out.println(getName() + "正在使用o2,等待o1");
                        synchronized(o1) {
                            System.out.println(getName() + "等到o1,执行成功");
                        }
                    }
                }               
            }
        }.start();
    }
}
/*
 *  在JDK1.8中输出结果为:
 *  ----------------------
    线程A正在使用o1,等待o2
    线程A等到o2,执行成功
    线程A正在使用o1,等待o2
    线程B正在使用o2,等待o1
    -------------------------
 * */

20. 多线程和队列实现买卖票

Queue接口
public interface Queue {
    
    public void append(Object obj)throws Exception;
    
    public Object delete()throws Exception;

    public Object getFront()throws Exception;   
    
    public boolean isEmpty();
}
Class MyQueue
public class MyQueue implements Queue{
        
        //1 设置队列的默认长度
        
        static final int DEFAULT_SIZE=10;  //默认长度为10
        
        //2 设置队头
        
        int front; 
        
        //3 设置队尾
        
        int rear;
        
        //4 定义统计元素的变量
        
        int count;
        
        //5 队的最大长度
        
        int maxSize;
        
        Object[] queue;  //设置队列
        
        //空构造
        public MyQueue() {
            
            this.init(DEFAULT_SIZE);  //用户给定长度 默认长度为10
        }
        
        
        //有参数的构造
        public MyQueue(int size) {
            
            this.init(size);  //开辟用户给定的长度
        }
        
        /**
         * 初始化方法
         * @param size
         */
        public void init(int size) {
            
            //初始化属性
            this.maxSize=size;  //外部传进来的size
            
            //空队列
            front=rear=0;
            
            count=0;
            
            queue=new Object[size];
        }
        
        @Override
        public void append(Object obj) throws Exception {
            // TODO Auto-generated method stub
            //首先队列是否已满
            if(count>0&&front==rear) {  //判断队列是否已满
                
                throw new Exception("队列已满");
            }
            
            this.queue[rear]=obj;
            rear=(rear+1)%maxSize;
            count++;
        }

        @Override
        public Object delete() throws Exception {
            // TODO Auto-generated method stub
            if(this.isEmpty()) {
                
                throw new Exception("队列为空队");
            }
            
            Object obj=this.queue[front];
            front=(front+1)%maxSize;
            count--;
            
            return obj;
            
        }

        @Override
        public Object getFront() throws Exception {
            // TODO Auto-generated method stub
            if(!this.isEmpty()) {
                
                return this.queue[front];
            }
            return null;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return this.count==0;
        }
    }
Class WindowQueue
public class WindowQueue { //卖票的窗口

    //定义卖票队列
    
    int maxSize=10;
    
    MyQueue queue=new MyQueue(maxSize);
    
    int num=0; //最多卖100张票
    
    boolean flag=true ; //判断是否继续卖票
    
    
    //排队买票
    public synchronized void producer()throws Exception{
        
        if(this.queue.count<maxSize) {
            
            this.queue.append(num++); //等待买票的数量++
            System.out.println("第"+num+"个客户排队买票");
            this.notifyAll(); //唤醒等待的线程
        }else {
            
            System.out.println("队列已满 请等待");
            this.wait(); 
        }
    }
    
    
    //卖票
    public synchronized void consumer()throws Exception{
        
        if(this.queue.count>0) {
            Object obj=this.queue.delete();  //出队
            int temp=Integer.parseInt(obj.toString());
            System.out.println("第"+(temp+1)+"个客户买到票离开队列");
            
            //如果当前的队列为空 并且卖出票数大于100
            if(this.queue.isEmpty()&&this.num>=100) {
                
                this.flag=false;
            }
            this.notifyAll(); //唤醒等待的线程
        }else {
            
            System.out.println("队列已空 请等待");
            this.wait();
        }
    }
}
Class Producer
public class Producer implements Runnable{

    WindowQueue queue;
    
    public Producer(WindowQueue queue) {
        
        this.queue=queue;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(queue.num<100) {  //必须小于100张票 才可以买票
        try {
            Thread.sleep(1000);
            queue.producer();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }

}
Class Consumer
public class Consumer implements Runnable{
    
    WindowQueue queue;
    
    public Consumer(WindowQueue queue) {
        
        this.queue=queue;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(queue.flag) {  //如果队列为空 并且票数大于100 就不会卖票了
            
            try {
                Thread.sleep(1000);
                queue.consumer();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
Class QueueTest
public class QueueTest {        
    public static void main(String[] args) throws Exception {       
        WindowQueue queue=new WindowQueue();
        Producer p=new Producer(queue);
        
        Consumer con=new Consumer(queue);
        
        //以上的代码一定要注意 传入的是同一个对象
        
        Thread t1=new Thread(p);
        
        Thread t2=new Thread(con);
        
        
        t1.start();
        
        t2.start();
    }
}

Lambda表达式

上一篇 下一篇

猜你喜欢

热点阅读