美文网首页
JAVA(四)回忆基础扫盲多线程

JAVA(四)回忆基础扫盲多线程

作者: 文子轩 | 来源:发表于2018-06-27 12:53 被阅读10次

    一.多线程的小例子

    import org.junit.Test;
    
    public class TestThread {    
    @Test
      public void test1(){
      实例化线程对象
          new MyThread("T1").start();
          new MyThread("T2").start();
      }
      定义线程类实现类
    class MyThread extends Thread{
        private String name ;
         构造函数传入值,获取线程的名称
        public MyThread(String name) {
            this.name = name;
        }
         初始化线程执行条数
        public void run() {
            for(int i = 0; i <= 100 ; i ++){
                System.out.println(name + " : " + i);
                yield();
            }
        }
    }
    

    }

    四.构建线程池

    import java.util.LinkedList;
    票池,创建
    public class TicketPool {
    定义pool池,使其是链表对象
    private LinkedList<Integer> pool = new LinkedList<Integer>();
    生产方法
    public /*synchronized*/ int add(Integer i){
        pool.add(i);
        return i ;
     }
    消费方法
    public /*synchronized*/ int remove(){
        try {
            while(pool.isEmpty()){
                Thread.sleep(50);  缓解进程抢占问题
            }
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pool.removeFirst();
       }
    }
    

    五.消费者类

    public class Consumer extends Thread {
    private String name ;
     
    private TicketPool pool ;
    获取线程的name和pool实例
    public Consumer(String name,TicketPool pool) {
        super();
        this.name = name;
        this.pool = pool ;
    }
    定义执行方法
    public void run() {
        while(true){
            int n = pool.remove();
            System.out.println(name + " remove : " + n);
           }
      }
    }
    

    六.生产者类

    public class Producer extends Thread {
        private static int index = 0 ;
        private String name ;
     
    private TicketPool pool ;
     
    public Producer(String name,TicketPool pool) {
        super();
        this.name = name;
        this.pool = pool ;
    }
    
    public void run() {
        while(true){
            int n = pool.add(index ++ );
            System.out.println(name + " add : " + n);
        }
    }
    

    }

    七.定义执行函数类

    public class App {
    
    public static void main(String[] args) {
        TicketPool pool = new TicketPool();
        Producer p1 = new Producer("P1", pool);
        Producer p2 = new Producer("P2", pool);
        Consumer c1 = new Consumer("C1", pool);
         
        p1.start();
        p2.start();
        c1.start();
    }
    

    }

    相关文章

      网友评论

          本文标题:JAVA(四)回忆基础扫盲多线程

          本文链接:https://www.haomeiwen.com/subject/pdebyftx.html