• 线程(一)


    package com.bjsxt.thread.create;
    /**
     * 模拟龟兔赛跑
     1、创建多线程  继承  Thread  +重写run(线程体)
     2、使用线程: 创建子类对象 + 对象.start()  线程启动
         
     * 
     * @author Administrator
     *
     */
    public class Rabbit extends Thread {
        @Override
        public void run() {
            //线程体
            for(int i=0;i<100;i++){
                System.out.println("兔子跑了"+i+"步");
            }
        }
    }
    class Tortoise extends Thread {
    
        @Override
        public void run() {
            //线程体
            for(int i=0;i<100;i++){
                System.out.println("乌龟跑了"+i+"步");
            }
        }
    }
    package com.bjsxt.thread.create;
    
    public class RabbitApp {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            //创建子类对象
            Rabbit rab = new Rabbit();
            Tortoise tor =new Tortoise();
            
            
            //调用start 方法
            rab.start(); //不要调用run方法
            //rab.run();
            tor.start();
            //tor.run();
            
            for(int i=0;i<1000;i++){
                System.out.println("main==>"+i);
            }
        }
    
    }

    静态代理:

    package com.bjsxt.thread.create;
    /**
     * 静态代理 设计模式
     * 1、真实角色
     * 2、代理角色: 持有真实角色的引用
     * 3、二者 实现相同的接口
     * 
     * @author Administrator
     *
     */
    public class StaticProxy {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            //创建真实角色
            Marry you =new You();
            //创建代理角色 +真实角色的引用
            WeddingCompany company =new WeddingCompany(you);
            //执行任务
            company.marry();
        }
    
    }
    //接口
    interface Marry{
        public abstract void marry();
    }
    //真实角色
    class You implements Marry{
    
        @Override
        public void marry() {
            System.out.println("you and  嫦娥结婚了....");
        }
        
    }
    //代理角色
    class WeddingCompany implements Marry{
        private Marry you;
        public WeddingCompany() {
        }
        
        public WeddingCompany(Marry you) {
            this.you = you;
        }
        private void before(){
            System.out.println("布置猪窝....");
            
        }
        private void after(){
            System.out.println("闹玉兔....");
        }
        @Override
        public void marry() {
            before();
            you.marry();
            after();
        }
        
    }
    package com.bjsxt.thread.create;
    /**
     推荐  Runnable 创建线程
     1)、避免单继承的局限性
     2)、便于共享资源
      
      
      使用 Runnable 创建线程
      1、类 实现 Runnable接口 +重写 run()   -->真实角色类
      2、启动多线程  使用静态代理
        1)、创建真实角色
        2)、创建代理角色 +真实角色引用
        3)、调用 .start() 启动线程
      
      
     * @author Administrator
     *
     */
    public class Programmer implements Runnable {
        @Override
        public void run() {
            for(int i=0;i<1000;i++){
                System.out.println("一边敲helloworld....");
            }
        }
    }
    package com.bjsxt.thread.create;
    
    public class ProgrammerApp {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
             //1)、创建真实角色
            Programmer pro =new Programmer();        
              //2)、创建代理角色 +真实角色引用
            Thread proxy =new Thread(pro);
              //3)、调用 .start() 启动线程
            proxy.start();
            
            for(int i=0;i<1000;i++){
                System.out.println("一边聊qq....");
            }
        }
    
    }
    package com.bjsxt.thread.create;
    /**
     * 方便共享资源
     * @author Administrator
     *
     */
    public class Web12306 implements Runnable {
        private int num =50;
    
        @Override
        public void run() {
            while(true){
                if(num<=0){
                    break; //跳出循环
                }
                System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
            }
        }
        
        public static void main(String[] args) {
            //真实角色
            Web12306 web = new Web12306();
            //代理
            Thread t1 =new Thread(web,"路人甲");
            Thread t2 =new Thread(web,"黄牛已");
            Thread t3 =new Thread(web,"攻城师");
            //启动线程
            t1.start();
            t2.start();
            t3.start();
        }
    }
    package com.bjsxt.thread.status;
    
    public class StopDemo01 {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Study s =new Study();
            new Thread(s).start();
            
            //外部干涉
            for(int i=0;i<100;i++){
                if(50==i){ //外部干涉
                    s.stop();
                }
                System.out.println("main.....-->"+i);
            }
        }
    
    }
    class Study implements Runnable{
         //1)、线程类中 定义 线程体使用的标识     
        private boolean flag =true;
        @Override
        public void run() {
            //2)、线程体使用该标识
            while(flag){
                System.out.println("study thread....");
            }
        }
        //3)、对外提供方法改变标识
        public void stop(){
            this.flag =false;
        }
        
    }
    阻塞:
    package com.bjsxt.thread.status;
    /**
     * join:合并线程
     * @author Administrator
     *
     */
    public class JoinDemo01 extends Thread {
    
        /**
         * @param args
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws InterruptedException {
            JoinDemo01 demo = new JoinDemo01();
            Thread t = new Thread(demo); //新生
            t.start();//就绪
            //cpu调度 运行
            
            
            for(int i=0;i<1000;i++){
                if(50==i){
                    t.join(); //main阻塞...
                }
                System.out.println("main...."+i);
            }
        }
        
        @Override
        public void run() {
            for(int i=0;i<1000;i++){
                System.out.println("join...."+i);
            }
        }
    
    }
    package com.bjsxt.thread.status;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * 倒计时
     * 1、倒数10个数,一秒内打印一个
     * 2、倒计时
     * @author Administrator
     *
     */
    public class SleepDemo01 {
    
        /**
         * @param args
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws InterruptedException {
            Date endTime =new Date(System.currentTimeMillis()+10*1000);
            long end =endTime.getTime();
            while(true){
                //输出
                System.out.println(new SimpleDateFormat("mm:ss").format(endTime));
                //等待一秒
                Thread.sleep(1000);
                //构建下一秒时间
                endTime =new Date(endTime.getTime()-1000);
                //10秒以内 继续 否则 退出
                if(end-10000>endTime.getTime()){
                    break;
                }
            }
        }
        public static void test1() throws InterruptedException{
            int num =10;
            while(true){
                System.out.println(num--);
                Thread.sleep(1000); //暂停
                if(num<=0){
                    break;
                }
            }
        }
        
    
    }
    package com.bjsxt.thread.status;
    
    
    /**
     * Sleep模拟 网络延时  线程不安全的类
     * @author Administrator
     *
     */
    public class SleepDemo02 {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            //真实角色
            Web12306 web= new Web12306();
            Web12306 web2 = new Web12306();
            //代理
            Thread t1 =new Thread(web,"路人甲");
            Thread t2 =new Thread(web,"黄牛已");
            Thread t3 =new Thread(web,"攻城师");
            //启动线程
            t1.start();
            t2.start();
            t3.start();
        }
    
    }
    
    class Web12306 implements Runnable {
        private int num =50;
    
        @Override
        public void run() {
            while(true){
                if(num<=0){
                    break; //跳出循环
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
            }
        }
        
        
    }
    package com.bjsxt.thread.info;
    /**
     *
      Thread.currentThread()     :当前线程
      setName():设置名称
      getName():获取名称
      isAlive():判断状态
    
     * @author Administrator
     *
     */
    public class InfoDemo01 {
    
        /**
         * @param args
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws InterruptedException {
            MyThread it =new MyThread();
            Thread proxy =new Thread(it,"挨踢");
            proxy.setName("test");
            System.out.println(proxy.getName());
            System.out.println(Thread.currentThread().getName()); //main
            
            proxy.start();
            System.out.println("启动后的状态:"+proxy.isAlive());
            Thread.sleep(200);
            it.stop();
            Thread.sleep(100);
            System.out.println("停止后的状态:"+proxy.isAlive());
        }
    
    }
    package com.bjsxt.thread.info;
    /**
     * 优先级:概率,不是绝对的先后顺序
       MAX_PRIORITY  10
       NORM_PRIORITY 5 (默认)
       MIN_PRIORITY  1
       
       setPriority()
       getPriority()
     * @author Administrator
     *
     */
    public class InfoDemo02 {
    
        /**
         * @param args
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws InterruptedException {
            MyThread it =new MyThread();
            Thread p1 =new Thread(it,"挨踢1");
            MyThread it2 =new MyThread();
            Thread p2 =new Thread(it2,"挨踢2");
            
            p1.setPriority(Thread.MIN_PRIORITY); //设置优先级
            p2.setPriority(Thread.MAX_PRIORITY);//设置优先级
            p1.start();
            p2.start();
            Thread.sleep(100);
            it.stop();
            it2.stop();
        }
    
    }
    package com.bjsxt.thread.info;
    
    public class MyThread implements Runnable {
        private boolean flag =true;
        private int num =0;
        @Override
        public void run() {
            while(flag){
                System.out.println(Thread.currentThread().getName()+"-->"+num++);
            }
        }
        public void stop(){
            this.flag=!this.flag;
        }
    }
    package com.bjsxt.thread.syn;
    /**
     * 单例设计模式:确保一个类只有一个对象
     * @author Administrator
     *
     */
    public class SynDemo02 {
        /**
         * @param args
         */
        public static void main(String[] args) {
            JvmThread thread1 = new JvmThread(100);
            JvmThread thread2 = new JvmThread(500);
            thread1.start();
            thread2.start();
            
        }
    
    }
    class JvmThread extends Thread{
        private long time;
        public JvmThread() {
        }
        public JvmThread(long time) {
            this.time =time;
        }
        @Override
        public void run() {        
            System.out.println(Thread.currentThread().getName()+"-->创建:"+Jvm.getInstance(time));
        }
    }
    
    
    /**
     * 单例设计模式
     * 确保一个类只有一个对象
     * 懒汉式  double checking
     * 1、构造器私有化,避免外部直接创建对象
     * 2、声明一个私有的静态变量
     * 3、创建一个对外的公共的静态方法 访问该变量,如果变量没有对象,创建该对象
     */
    class Jvm {
        //声明一个私有的静态变量
        private static Jvm instance =null;    
        //构造器私有化,避免外部直接创建对象
        private Jvm(){
            
        }
        //创建一个对外的公共的静态方法 访问该变量,如果变量没有对象,创建该对象
        public static Jvm getInstance(long time){
            // c d e  -->效率  提供 已经存在对象的访问效率
            if(null==instance){    
                // a b
                synchronized(Jvm.class){
                    if(null==instance ){
                        try {
                            Thread.sleep(time); //延时 ,放大错误
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        instance =new Jvm();
                    }
                }
          }//a
          return instance;
        }
        
        
        public static Jvm getInstance3(long time){
            //a b c d e  -->效率不高 c  存在对象也需要等待
            synchronized(Jvm.class){
                if(null==instance ){
                    try {
                        Thread.sleep(time); //延时 ,放大错误
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    instance =new Jvm();
                }
                return instance;
            }
        }
        
        
        public static synchronized Jvm getInstance2(long time){
            if(null==instance ){
                try {
                    Thread.sleep(time); //延时 ,放大错误
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                instance =new Jvm();
            }
            return instance;
        }
        
        
        
        public static Jvm getInstance1(long time){
            if(null==instance ){
                try {
                    Thread.sleep(time); //延时 ,放大错误
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                instance =new Jvm();
            }
            return instance;
        }
    }

    死锁:

    package com.bjsxt.thread.syn;
    /**
     * 过多的同步方法可能造成死锁
     * @author Administrator
     *
     */
    public class SynDemo03 {
        /**
         * @param args
         */
        public static void main(String[] args) {
            Object g =new Object();
            Object m = new Object();
            Test t1 =new Test(g,m);
            Test2 t2 = new Test2(g,m);
            Thread proxy = new Thread(t1);
            Thread proxy2 = new Thread(t2);
            proxy.start();
            proxy2.start();
        }
    }
    class Test implements Runnable{
        Object goods ;
        Object money ;
        public Test(Object goods, Object money) {
            super();
            this.goods = goods;
            this.money = money;
        }
        @Override
        public void run() {
            while(true){
                test();
            }
        }
        public void test(){
            synchronized(goods){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(money){
                }
            }
            System.out.println("一手给钱");
        }
    }
    class Test2  implements Runnable{
        Object goods ;
        Object money ;
        public Test2(Object goods, Object money) {
            super();
            this.goods = goods;
            this.money = money;
        }
        @Override
        public void run() {
            while(true){
                test();
            }
        }
        public void test(){
            synchronized(money){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(goods){
                    
                }
            }
            System.out.println("一手给货");
        }
        
    }

    生产消费者模式:

    package com.bjsxt.thread.pro;
    /**
     一个场景,共同的资源
      生产者消费者模式 信号灯法
     wait() :等待,释放锁   sleep 不释放锁
     notify()/notifyAll():唤醒
      与 synchronized
     * @author Administrator
     *
     */
    public class Movie {
        private String pic ;
        //信号灯
        //flag -->T 生产生产,消费者等待 ,生产完成后通知消费
        //flag -->F 消费者消费 生产者等待, 消费完成后通知生产
        private boolean flag =true;
        /**
         * 播放
         * @param pic
         */
        public synchronized void play(String pic){
            if(!flag){ //生产者等待
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //开始生产
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("生产了:"+pic);
            //生产完毕        
            this.pic =pic;
            //通知消费
            this.notify();
            //生产者停下
            this.flag =false;
        }
        
        public synchronized void watch(){
            if(flag){ //消费者等待
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //开始消费
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费了"+pic);
            //消费完毕
            //通知生产
            this.notifyAll();
            //消费停止
            this.flag=true;
        }
    }
    package com.bjsxt.thread.pro;
    /**
     * 生产者
     * @author Administrator
     *
     */
    public class Player implements Runnable {
        private Movie m ;
        
        public Player(Movie m) {
            super();
            this.m = m;
        }
    
        @Override
        public void run() {
            for(int i=0;i<20;i++){
                if(0==i%2){
                    m.play("左青龙");
                }else{
                    m.play("右白虎");
                }
            }
        }
    
    }
    package com.bjsxt.thread.pro;
    
    public class Watcher implements Runnable {
        private Movie m ;
        
        public Watcher(Movie m) {
            super();
            this.m = m;
        }
    
        @Override
        public void run() {
            for(int i=0;i<20;i++){
                m.watch();
            }
        }
    
    }
    package com.bjsxt.thread.pro;
    
    public class App {
        public static void main(String[] args) {
            //共同的资源
            Movie m = new Movie();
            
            //多线程
            Player p = new Player(m);
            Watcher w = new Watcher(m);
            
            new Thread(p).start();        
            new Thread(w).start();
        }
    }
    package com.bjsxt.thread.pro;
    public class TestProduce {
        public static void main(String[] args) {
            SyncStack sStack = new SyncStack();
            Shengchan sc = new Shengchan(sStack);
            Xiaofei xf = new Xiaofei(sStack);
            sc.start();
            xf.start();
        }
    }
    
    class Mantou {
        int id;
        Mantou(int id){
            this.id=id;
        }
    }
    
    class SyncStack{
        int index=0;
        Mantou[] ms = new Mantou[10];
        
        public synchronized void push(Mantou m){
            while(index==ms.length){
                try {
                    this.wait(); 
                    //wait后,线程会将持有的锁释放。sleep是即使睡着也持有互斥锁。
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.notify(); //唤醒在当前对象等待池中等待的第一个线程。notifyAll叫醒所有在当前对象等待池中等待的所有线程。
            //如果不唤醒的话。以后这两个线程都会进入等待线程,没有人唤醒。
            ms[index]=m;
            index++;
        }
        public synchronized Mantou pop(){
            while(index==0){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.notify();
            index--;
            return ms[index];
        }
    }
    
    class Shengchan extends Thread{
        SyncStack ss = null;
        
        public Shengchan(SyncStack ss) {
            this.ss=ss;
        }
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                System.out.println("造馒头:"+i);
                Mantou m = new Mantou(i);
                ss.push(m);
            }
        }
    }
    
    class Xiaofei extends Thread{
        SyncStack ss = null;
        
        public Xiaofei(SyncStack ss) {
            this.ss=ss;
        }
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                Mantou m = ss.pop();
                System.out.println("吃馒头:"+i);
                
            }
        }
    }
    package com.bjsxt.thread.schedule;
    
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    /**
        了解
      Timer() 
      schedule(TimerTask task, Date time) 
      schedule(TimerTask task, Date firstTime, long period) 
      自学 quartz
     * @author Administrator
     *
     */
    public class TimeDemo01 {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Timer timer =new Timer();
            timer.schedule(new TimerTask(){
    
                @Override
                public void run() {
                    System.out.println("so easy....");
                }}, new Date(System.currentTimeMillis()+1000), 200);
        }
    
    }
  • 相关阅读:
    A1051 Pop Sequence (25 分)
    A1060 Are They Equal (25分)
    A1063 Set Similarity (25分)
    A1037 Magic Coupon (25分)
    Mybatis获取插入记录的自增长ID
    压力测试工具ab的使用
    spring注解
    《spring技术内幕》读书笔记(1)——什么是POJO模式
    用HttpSessionListener统计在线用户或做账号在线人数管理
    (转)注释驱动的 Spring cache 缓存介绍
  • 原文地址:https://www.cnblogs.com/sunhan/p/4006507.html
Copyright © 2020-2023  润新知