多线程学习笔记2

多线程

package thread;

public class ThreadTest1 extends Thread {
    @Override
    public void run() {//重写run方法
        for (int i = 0; i < 200; i++) {
            System.out.println("我爱学习"+i);
        }
    }

    public static void main(String[] args) {
        ThreadTest1 test1 = new ThreadTest1();//创建一个线程对象
        test1.start();//开启线程
        for (int i = 0; i < 1000; i++) {
            System.out.println("我想睡觉"+i);//方法的处理,由CPU决定
        }
    }
}

一般使用Runnable的实现类来运用线程,因为一个对象可以运行多个线程。

package thread;

public class ThreadTest03 implements Runnable {
    private  int ticketnums=10;
    @Override
    public void run() {
        while (true){
            if (ticketnums<=0){
                break;//判定跳出循环的条件
            }
            try {
                Thread.sleep(200);//模拟延时
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketnums--+"张票。");
        }
    }

    public static void main(String[] args) {
        ThreadTest03 test03 = new ThreadTest03();//实例化Runnable接口实现类
        new Thread(test03,"jack").start();//启动线程,开始分配工作。
        new Thread(test03,"lucy").start();
        new Thread(test03,"merry").start();
    }
}

龟兔赛跑

package thread;

public class Demo01 implements Runnable {
    private static String winner;
    @Override
    public void run() {
        for (int i = 0; i <=100; i++) {
            /*if (Thread.currentThread().getName().equals("兔子")&&i%50==0){
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/
            boolean flag=gameOver(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"米。");
        }

    }
    private boolean gameOver(int meter){
        if(winner!=null){
            return true;
        }{
            if (meter>=100){
                winner=Thread.currentThread().getName();
                System.out.println("winner is"+winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Demo01 test04 = new Demo01();
        new Thread(test04,"兔子").start();
        new Thread(test04,"乌龟").start();
    }
}

静态代理:被代理者跟代理者同时实现一个接口,被代理者可通过代理者做很多自己额外做的事,从而减少被代理者的工作。

Lamda表达式:作用是为了较少匿名内部类的数量过多。一个接口只有一个抽象方法那么这个接口就是函数接口。可以通过拉姆达lamda来创建对象。去掉无用代码,只保留核心逻辑。

package lamda;

public class LamdaTest01 {
   static  class Like2 implements ILike{//静态内部类

       @Override
       public void lambda() {
           System.out.println("I like lambda12");
       }
   }

    public static void main(String[] args) {
        new Like().lambda();
        new Like2().lambda();
        class Like3 implements ILike{//局部内部类
            @Override
            public void lambda() {
                System.out.println("I like lambda13");
            }
        }
        new Like3().lambda();
        ILike like1=new ILike() {//匿名内部类
            //@Override
            public void lambda() 
            {
                System.out.println("I like lambda14");
            }
         };
         like1.lambda();
         like1=()-> {//Lambda简化
                System.out.println("I like lambda15");
            };//拉姆达和匿名内部类执行体之后加分号
        like1.lambda();

   }
}
interface ILike{
    void lambda();
}
class Like implements ILike{//接口实现类

    @Override
    public void lambda() {
        System.out.println("I like lambda11");
    }
}

匿名内部类:没有类名,必须借助接口或父类

进程停止操作

package lamda;

public class StopTest01 implements Runnable{
    private static boolean flag=true;
    @Override
    public void run() {
        int num=0;
        while (flag){
            System.out.println("RUN==========>Thread"+num);
        }

    }

    public static void main(String[] args) {
        StopTest01 test01 = new StopTest01();
        new Thread(test01).start();//进程停止
        for (int i = 0; i < 1000; i++) {
            System.out.println("main"+i);
            if (i==900){
                flag=false;
                System.out.println("进程停止");
            }
        }

    }
}

倒计时:一秒等于一千毫秒

package lamda;

public class TenDown {
    public static void main(String[] args) throws InterruptedException {
        try {
          tendown();
        } 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;
            }
        }
    }
}

获取当前时间

package lamda;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TenDown {
    public static void main(String[] args) throws InterruptedException {
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        while(true){
        try {
        Thread.sleep(1000);

        System.out.println(new SimpleDateFormat("hh:mm:ss").format(date));//设置时间格式
        //date = 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;
            }
        }
    }
}

线程礼让:不一定成功,看CPU的分配。

package lamda;

//import sun.security.mscapi.KeyStore;

public class YieldTest {
    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()+"线程结束");
    }
}

线程强制执行

package lamda;

public class JoinTest implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("VIP来了");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        JoinTest joinTest = new JoinTest();
        Thread thread=new Thread(joinTest);
        thread.start();
        for (int i = 0; i < 100; i++) {
            if (i==50){
          thread.join();
        }
            System.out.println("正常排队"+i);
        }
    }
}

观察线程状态:线程一旦死亡,不能重新开启。

package lamda;

public class StateTest {
    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);//开始状态
        thread.start();
        state = thread.getState();//运行状态
        System.out.println(state);
        while (state!=Thread.State.TERMINATED){
            Thread.sleep(100);
            state = thread.getState();//更新状态
            System.out.println(state);
        }


    }
}

设置线程优先级:1~10数字越大优先级越高,先设置后启动。

package lamda;

public class PriorityTest {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+">>>>"+Thread.currentThread().getPriority());
        MyPriority myPriority = new MyPriority();
        Thread thread1 = new Thread(myPriority);
        Thread thread2 = new Thread(myPriority);
        Thread thread3 = new Thread(myPriority);
        thread1.setPriority(1);
        thread1.start();
        thread2.setPriority(5);
        thread2.start();
        thread3.setPriority(10);
        thread3.start();
    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+">>>>"+Thread.currentThread().getPriority());
    }
}

守护线程:虚拟机只对用户线程负责,不对守护线程负责,用户线程使用完毕及关闭

package lamda;

import java.awt.*;

public class DaemoTest {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();
        Thread thread = new Thread(god);
        thread.setDaemon(true);
        thread.start();
        new Thread(you).start();


    }
}
class God implements Runnable{
    @Override
    public void run() {
        System.out.println("=========上帝守护=============");
    }
}
class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 365; i++) {
            System.out.println("开开心心每一天"+i);
        }
        System.out.println("GoodBye");
    }
}

并发:同一对象被多个线程操作

线程同步就是一个等待机制。线程安全:队列+锁。synchronized锁住变化的量,增删改的量可以锁方法,也可以锁任意代码块synchronized(obj){变化的量}

CopyOnWriterArrayList是对集合增强安全性。

死锁DeadLock:两个线程都想要对方所占用的资源,而自己却不释放对方所要使用的资源形成的一种僵持状态。

package thread;

//import com.sun.org.apache.xpath.internal.operations.String;

public class DeadLock {
    public static void main(String[] args) {
        MakeUp g1 = new MakeUp(0, "小红");
        MakeUp g2 = new MakeUp(5, "小蓝");
        g1.start();
        g2.start();

    }
}
class LickTip{}
class Mirror{}
class MakeUp extends Thread{
    static LickTip licktip=new LickTip();//保证资源只有一份使用static关键字
    static Mirror mirror=new Mirror();
    int choice;
    String girlName;

     MakeUp(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
     makeup();
    }
    private void makeup(){
        if (choice==0){
            synchronized (licktip){
            System.out.println(this.girlName+"拿到了口红");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (mirror){
                    System.out.println(this.girlName+"拿到了镜子");
            }

        }
   }
   else {
            synchronized (mirror){
                System.out.println(this.girlName+"拿到了镜子");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (licktip){
                    System.out.println(this.girlName+"拿到了口红");
                }
            }

        }

}}

解决死锁方法

package thread;

//import com.sun.org.apache.xpath.internal.operations.String;

public class DeadLock {
    public static void main(String[] args) {
        MakeUp g1 = new MakeUp(0, "小红");
        MakeUp g2 = new MakeUp(5, "小蓝");
        g1.start();
        g2.start();

    }
}
class LickTip{}
class Mirror{}
class MakeUp extends Thread{
    static LickTip licktip=new LickTip();//保证资源只有一份使用static关键字
    static Mirror mirror=new Mirror();
    int choice;
    String girlName;

     MakeUp(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
     makeup();
    }
    private void makeup(){
        if (choice==0){
            synchronized (licktip){
            System.out.println(this.girlName+"拿到了口红");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


        }synchronized (mirror){
                System.out.println(this.girlName+"拿到了镜子");
            }
   }
   else {
            synchronized (mirror){
                System.out.println(this.girlName+"拿到了镜子");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (licktip){
                System.out.println(this.girlName+"拿到了口红");
            }
        }

}}

你可能感兴趣的:(学习,笔记,java)