java多线程1

多线程

实现多线程

package com.ding.demo1;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:22
 * @Version 1.0
 */
public class MyThread  extends Thread {

    @Override
    public void run() {
        //代码就是线程在开启之后执行的代码
        for (int i = 0; i < 100; i++) {
            System.out.println("线程开启了"+i);
        }
    }
}


package com.ding.demo1;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:25
 * @Version 1.0
 */
public class Demo {
    public static void main(String[] args) {

        //创建一个线程对象
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();

        //开启一条线程
        t1.start();
        //开启第二条线程
        t2.start();
    }

}


package com.ding.demo2;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:28
 * @Version 1.0
 */
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName()+"第二种实现多线程"+ i);
        }
    }
}


package com.ding.demo2;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:29
 * @Version 1.0
 */
public class Demo {
    public static void main(String[] args) {
        //创建了一个参数的对象
        MyRunnable mr = new MyRunnable();
        //创建了一个多线程对象,并把参数传递给这个线程
        //在线程启动之后,执行的就是参数里面的run方法
        Thread t1 = new Thread();

        //开启线程
        t1.start();

        MyRunnable mr2 = new MyRunnable();
        Thread t2 = new Thread(mr2);
        t2.start();
    }
}

package com.ding.demo3;

import java.util.concurrent.Callable;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:37
 * @Version 1.0
 */
public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {

        for (int i = 0; i < 100; i++) {
            System.out.println("跟女孩表白"+ i);
        }

        //返回值是表示多线程运行完毕之后的结果
        return "答应";
    }
}


package com.ding.demo3;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:39
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //线程开启后需要执行里面多的call方法
        MyCallable mc = new MyCallable();

        //可以获取线程执行完毕之后的结果,也可以作为参数传递给Thread对象
        FutureTask<String> ft = new FutureTask<>(mc);

        //创建线程对象
        Thread t1 = new Thread(ft);

        //开启线程
        t1.start();

        String s = ft.get();

        System.out.println(s);
    }
}

获取线程名称

package com.ding.demo4;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:49
 * @Version 1.0
 */
public class MyThread extends Thread{

    public MyThread() {
    }

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {

        for (int i = 0; i < 100; i++) {
            System.out.println(getName()+"-----"+i);
        }
    }
}



package com.ding.demo4;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 16:50
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {
        //1,线程是有默认名字的,格式:Thread-编号

        MyThread t1=new MyThread("小明");
        MyThread t2=new MyThread("小红");

        t1.start();
        t2.start();

    }
}

package com.ding.demo5;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 17:03
 * @Version 1.0
 */
public class Demo {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
    }
}

线程休眠

package com.ding.demo6;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 17:05
 * @Version 1.0
 */
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName()+"---"+ i);
        }
    }
}



package com.ding.demo6;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 17:07
 * @Version 1.0
 */
public class Demo {
    public static void main(String[] args) throws InterruptedException {

/*        System.out.println("睡觉前");
        Thread.sleep(3000);
        System.out.println("睡觉后");*/

     MyRunnable mr =new MyRunnable();

        Thread t1 = new Thread(mr);
        Thread t2 = new Thread(mr);

        t1.start();
        t2.start();
    }
}

线程优先级

package com.ding.demo7;

import java.util.concurrent.Callable;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 17:37
 * @Version 1.0
 */
public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "---" + i);
        }
        return "线程执行完毕了";
    }
}



package com.ding.demo7;

import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:08
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {

        MyCallable mc = new MyCallable();

        FutureTask<String> ft = new FutureTask<>(mc);

        Thread t1=new Thread(ft);
        t1.setName("飞机");
        t1.setPriority(10);//优先级:1-10 默认值5
        t1.start();

        MyCallable mc2 = new MyCallable();

        FutureTask<String> ft2 = new FutureTask<>(mc2);

        Thread t2=new Thread(ft2);
        t2.setName("坦克");
        t2.setPriority(1);//优先级:1-10 默认值5
        t2.start();


    }
}

守护线程

package com.ding.demo8;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:19
 * @Version 1.0
 */
public class MyThread2 extends Thread{

    @Override
    public void run() {

        for (int i = 0; i < 100; i++) {
            System.out.println(getName()+"---"+i);
        }
    }
}



package com.ding.demo8;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:18
 * @Version 1.0
 */
public class MyThread1 extends Thread {

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println(getName()+"----"+i);
        }
    }
}


package com.ding.demo8;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:20
 * @Version 1.0
 */
public class Demo {
    public static void main(String[] args) {

        MyThread1 t1=new MyThread1();
        MyThread2 t2= new MyThread2();

        t1.setName("女神");
        t2.setName("备胎");

        //把第二个线程设置为守护线程
        //当普通线程执行完之后,那么守护线程也没有继续运行下去的必要

        t2.setDaemon(true);

        t1.start();
        t2.start();
    }
}


线程同步

package com.ding.demo9;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:26
 * @Version 1.0
 */
public class Ticket implements Runnable {

    //票的数量
    private  int ticket=100;
    private  Object obj=new Object();

    @Override
    public void run() {
        while (true){

            synchronized (obj){//多个线程必须使用同一把锁
                if(ticket<=0){

                    //卖完了
                    break;
                }else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    ticket--;
                    System.out.println(Thread.currentThread().getName()+"在卖票,还剩下"+ticket+"张票");

                }

            }
        }
    }
}



package com.ding.demo9;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:32
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {

        Ticket ticket =new Ticket();

        Thread t1 = new Thread(ticket);
        Thread t2 = new Thread(ticket);
        Thread t3 = new Thread(ticket);

        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

        t1.start();
        t2.start();
        t3.start();
    }
}


package com.ding.demo10;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:48
 * @Version 1.0
 */
public class MyThread extends Thread{
    private static int ticketCount=500;
    private static Object obj=new Object();

    @Override
    public void run() {
        while(true){
            synchronized (obj){ //就是当前的线程对象.
                if(ticketCount <= 0){
                    //卖完了
                    break;
                }else{
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticketCount--;
                    System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticketCount + "张票");
                }
            }
        }
    }
}


package com.ding.demo10;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:50
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {
        MyThread t1=new MyThread();
        MyThread t2=new MyThread();

        t1.setName("窗口一");
        t2.setName("窗口二");

        t1.start();

        t2.start();
    }
}

解决数据安全

package com.ding.demo11;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/31 19:56
 * @Version 1.0
 */
public class MyRunnable implements Runnable {
    private static int ticketCount=100;


    @Override
    public void run() {

        while (true){

            if ("窗口一".equals(Thread.currentThread().getName())){

                //同步方法
                boolean result=synchronizedMethod();
                if (result){
                    break;
                }
            }


            if ("窗口二".equals(Thread.currentThread().getName())){

                //同步代码块
                synchronized (MyRunnable.class){
                    if (ticketCount==0){
                        break;
                    }else {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        ticketCount--;
                        System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticketCount + "张票");
                    }
                }
            }
        }
    }

    private static synchronized boolean synchronizedMethod(){

        if (ticketCount==0){
            return true;
        }else{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ticketCount--;
            System.out.println(Thread.currentThread().getName()+"在卖票,还剩下"+ticketCount+"张票");
            return false;
        }
    }

}


package com.ding.demo11;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 08:17
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();

        Thread t1 = new Thread(mr);
        Thread t2 = new Thread(mr);

        t1.setName("窗口一");
        t2.setName("窗口二");

        t1.start();
        t2.start();
    }
}

Lock锁

package com.ding.demo12;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description Lock锁
 * @Author 丁帅帅
 * @Date 21/08/01 08:26
 * @Version 1.0
 */

public class Ticket implements Runnable {
    //票的数量
    private int ticket = 100;
    private Object obj = new Object();
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {

            try {
                lock.lock();
                if (ticket <= 0) {
                    //卖完了
                    break;
                } else {
                    Thread.sleep(100);
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticket + "张票");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }
}



package com.ding.demo12;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 08:32
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {

        Ticket ticket =new Ticket();

        Thread t1 =new Thread(ticket);
        Thread t2 =new Thread(ticket);
        Thread t3 =new Thread(ticket);

        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

        t1.start();
        t2.start();
        t3.start();
    }
}

死锁

package com.ding.demo13;

/**
 * @Description 死锁
 * @Author 丁帅帅
 * @Date 21/08/01 08:40
 * @Version 1.0
 */
public class demo {

    public static void main(String[] args) {

        Object oa = new Object();
        Object ob = new Object();

        new Thread(()->{

            while (true){
                synchronized (oa){
                    synchronized (ob){
                        System.out.println("小康正在赶路");
                    }
                }
            }
        }).start();


        new Thread(()->{

            while (true){

                synchronized (ob){

                    synchronized (oa){
                        System.out.println("小红同学正在赶路");
                    }
                }
            }
        }).start();
    }
}

案例

package com.ding.demo14;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 08:45
 * @Version 1.0
 */
public class Cooker extends Thread {
//    生产者步骤:
//            1,判断桌子上是否有汉堡包
//    如果有就等待,如果没有才生产。
//            2,把汉堡包放在桌子上。
//            3,叫醒等待的消费者开吃。


    @Override
    public void run() {

        while (true){
            synchronized (Desk.lock){
                if (Desk.count==0){
                    break;
                }else {
                    if (!Desk.flag){

                        //生产
                        System.out.println("厨师正在生产汉堡包");
                        Desk.flag=true;
                        Desk.lock.notifyAll();
                    }else {
                        try {
                            Desk.lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

package com.ding.demo14;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 08:57
 * @Version 1.0
 */
public class Foodie extends Thread {

    @Override
    public void run() {
//        1,判断桌子上是否有汉堡包。
//        2,如果没有就等待。
//        3,如果有就开吃
//        4,吃完之后,桌子上的汉堡包就没有了
//                叫醒等待的生产者继续生产
//        汉堡包的总数量减一

        while (true){
            synchronized (Desk.lock){
                if (Desk.count==0){
                    break;
                }else {
                    if (Desk.flag){

                        //有
                        System.out.println("吃货在吃汉堡包");
                        Desk.flag=false;
                        Desk.lock.notifyAll();
                        Desk.count--;
                    }else{
                        //没有就等待
                        try {
                            Desk.lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

package com.ding.demo14;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 08:47
 * @Version 1.0
 */
public class Desk {

    //定义一个标记
    //true 就表示桌子上有汉堡包
    //false 就表示桌子上没有汉堡包,此时允许厨师执行

    public static boolean flag =false;

    //汉堡包的总数量
    public static  int count =10;

    //锁对象
    public static final Object lock =new Object();
}

package com.ding.demo14;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 09:08
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {
    /*消费者步骤:
        1,判断桌子上是否有汉堡包。
        2,如果没有就等待。
        3,如果有就开吃
        4,吃完之后,桌子上的汉堡包就没有了
                叫醒等待的生产者继续生产
        汉堡包的总数量减一*/


        /*生产者步骤:
        1,判断桌子上是否有汉堡包
        如果有就等待,如果没有才生产。
        2,把汉堡包放在桌子上。
        3,叫醒等待的消费者开吃。*/


        Foodie f=new Foodie();
        Cooker c=new Cooker();

        f.start();
        c.start();
    }
}

优化

package com.ding.demo15;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 09:26
 * @Version 1.0
 */
public class Desk {

    private boolean flag;

    private int count;

    private final Object lock = new Object();

    public Desk() {
        this(false,10);
    }

    public Desk(boolean flag, int count) {
        this.flag = flag;
        this.count = count;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Object getLock() {
        return lock;
    }

    @Override
    public String toString() {
        return "Desk{" +
                "flag=" + flag +
                ", count=" + count +
                ", lock=" + lock +
                '}';
    }
}

package com.ding.demo15;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 09:38
 * @Version 1.0
 */
public class Foodie extends Thread{

    private Desk desk;

    public Foodie(Desk desk) {
        this.desk = desk;
    }

    @Override
    public void run() {

        while (true){
            synchronized (desk.getLock()){
                if (desk.getCount()==0){
                    break;
                }else{
                    if (desk.isFlag()){
                        //有
                        System.out.println("吃货再吃汉堡");
                        desk.setFlag(false);
                        desk.getLock().notifyAll();
                        desk.setCount(desk.getCount()-1);
                    }else{
                        //没有就等待
                        try {
                            desk.getLock().wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

package com.ding.demo15;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 09:45
 * @Version 1.0
 */
public class Cooker extends Thread{

    private Desk desk;

    public Cooker(Desk desk) {
        this.desk = desk;
    }


    @Override
    public void run() {

        while (true){
            synchronized (desk.getLock()){
                if(desk.getCount()==0){
                    break;
                }else {
                    if(!desk.isFlag()){
                        System.out.println("厨师正在生产汉堡包");
                        desk.setFlag(true);
                        desk.getLock().notifyAll();
                    }else{
                        try {
                            desk.getLock().wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

package com.ding.demo15;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/08/01 09:49
 * @Version 1.0
 */
public class Demo {

    public static void main(String[] args) {
        Desk desk = new Desk();

        Foodie f = new Foodie(desk);
        Cooker c = new Cooker(desk);

        f.start();
        c.start();

    }
}

posted @ 2021-08-01 12:07  丁帅帅dss  阅读(39)  评论(0)    收藏  举报