JavaThreadNote02

静态代理模式

public class StacticProxy {
    public static void main(String[] args) {
        You you = new You();//你要结婚

        new Thread(()-> System.out.println("Love You")).start();
        new WeddingCompany(new You()).HappyMarry();//简化了以下两句代码

        /*WeddingCompany weddingCompany = new WeddingCompany(new You());
        weddingCompany.HappyMarry();*/
    }
}

interface Marry {
    void HappyMarry();
}

//真实角色:要结婚的人
class You implements Marry {
    @Override
    public void HappyMarry() {
        System.out.println("I am happy to wedding!");
    }
}
//代理角色,帮助真实角色结婚
class WeddingCompany implements Marry {

    //代理who?(真实目标角色)
    private Marry targer;

    public WeddingCompany(Marry targer) {
        this.targer = targer;
    }

    @Override
    public void HappyMarry() {
        before();
        this.targer.HappyMarry();//真实对象
        after();
    }
    private void before() {
        System.out.println("准备结婚");
    }
    private void after() {
        System.out.println("结婚完成");
    }
}

总结:

  1. 真实对象和代理对象要实现同一个接口
  2. 代理对象要代理真实对象
  3. 优点:代理对象可以做许多真实对象无法做的事,真实对象专注做自己的事

Lambda表达式

public class TestLambda02 {
    public static void main(String[] args) {
        ILove love = null;
        //lambda表达式完整版
        love = (a) -> {
            System.out.println("I Love You--->" + a);
        };
        //简化版
        love = a -> System.out.println("I Love You--->" + a);
        love.love(520);
    }
}
interface ILove{
    void love(int a);
}

总结:

  1. lambds表达式只有一行时才能简化,否则要用代码块包裹
  2. 前提是接口为函数式接口(只包含一个抽象方法的接口)
  3. 多个参数也可以去掉参数类型,要去必须全去,且加上括号

线程停止

public class TestStop implements Runnable{

    //设置一个标志位
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("run...Thread--->"+i++);
        }
    }
    //2.设置公开的方法停止线程(切换标志位)
    public void stop() {
        flag = false;
    }
    
    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i <= 1000; i++) {
            System.out.println("main" + i);
            if (i == 900) {
                testStop.stop();
                System.out.println("线程即将停止!");
            }
        }
    }
}

总结:

  1. 建议线程正常停止--->利用次数,不建议死循环
  2. 建议使用标志位--->设置一个标志位
  3. 不要使用stop、destroy等过时或者JDK不建议使用的方法

线程休眠-sleep

一、模拟网络延迟:放大问题的发生性

public class TestSleep implements Runnable{
    //模拟延迟
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    public static void main(String[] args) {
        TestSleep ticket = new TestSleep();
    }
}

二、模拟倒计时

public class TestSleeo02 {
    public static void main(String[] args) {
        //打印当前系统时间
        Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
        while (true) {
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                startTime = new Date(System.currentTimeMillis());//更新当前时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void tenDown() throws InterruptedException {
        int num = 10;

        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
        }
    }
}

线程礼让-yield

礼让是让线程回到起点再同时开始,执行顺序仍由CPU决定,所以说礼让并不一定成功

public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }
}
class MyYield implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();//礼让
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}

线程强制执行-join(插队)

该方法了解即可,尽量少使用,会造成线程阻塞

public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程vip到达"+i);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        //启动线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();
        //主线程
        for (int i = 0; i < 500; i++) {
            if (i == 200) {
                thread.join();//插队
            }
            System.out.println("main" + i);
        }
    }
}

观测线程状态

一个线程只能启动一次,终止之后不能再次启动

public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("执行完毕!");
        });

        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);//NEW

        //启动线程
        thread.start();
        state = thread.getState();
        System.out.println(state);

        //监听
        while (state != Thread.State.TERMINATED) {
            Thread.sleep(100);
            state = thread.getState();//更新线程状态
            System.out.println(state);
        }
    }
}

线程优先级

设置优先级只会影响先后概率,并不是一定可以改变,因为执行的顺序由CPU决定

public class TestPriority {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());

        Mypriority mypriority = new Mypriority();

        Thread t1 = new Thread(mypriority);
        Thread t2 = new Thread(mypriority);
        Thread t3 = new Thread(mypriority);
        Thread t4 = new Thread(mypriority);

        //先设置优先级,再启动
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(1);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);
        t4.start();
    }
}
class Mypriority implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    }
}

转载请注明出处:http://www.bqysc.com/article/20230521/800440.html