Java之多线程(6个demo)

本文主要介绍Java中多线程,在Java中启动多线程的方法包括:继承Thread类或者实现Runnable接口,介绍了设置线程名称,设置线程优先级,设置守护线程等,介绍了线程同步,使用synchronized关键字和lock锁分别实现线程同步,解决线程安全问题,介绍了生产者和消费者模式,涉及线程延迟,等待,唤醒的方法。

目录

1-继承Thread类并重写run()方法实现多线程

2-线程控制(设置主线程和守护线程)

3-实现Runnable接口并重写run()方法实现多线程

4-三个线程实现窗口卖票的案例(synchronized实现线程同步)

5-Lock锁的方式是实现线程同步

6-生产者与消费者模式案例


1-继承Thread类并重写run()方法实现多线程

public class MyThread extends Thread{
    @Override
    public void run() {
        for(int i=0; i<50; i++) {
            System.out.println(Thread.currentThread().getName() + ":执行了");
        }
    }
}
public class ThreadDemo01 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread() ;
        MyThread myThread1 = new MyThread() ;
        //设置线程名
        myThread.setName("线程1");
        myThread1.setName("线程2");

        //设置线程优先级,线程 优先级默认是5,最小是1,最大是10
        myThread.setPriority(1);
        myThread1.setPriority(10);

        myThread.start();
        myThread1.start();
    }
}

2-线程控制(设置主线程和守护线程)

public class MyThread1 extends Thread {
    @Override
    public void run() {
        for(int i=1; i<=50; i++){
            System.out.println(Thread.currentThread().getName() + "执行了:" + i);
        }
    }
}
public class ThreadDemo02 {
    public static void main(String[] args) {
        MyThread1 my1 = new MyThread1() ;
        MyThread1 my2 = new MyThread1() ;

        my1.setName("关羽");
        my2.setName("张飞");
        Thread.currentThread().setName("刘备"); //主线程

        //设置为守护线程,当全部为守护线程时,线程终止
        my1.setDaemon(true);
        my2.setDaemon(true);

        my1.start();
        my2.start();

        for(int i=1; i<=50; i++){
            System.out.println(Thread.currentThread().getName() + "执行了:" + i);
        }


    }
}

3-实现Runnable接口并重写run()方法实现多线程

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        for(int i=0; i<50; i++){
            System.out.println(Thread.currentThread().getName() + "执行了:" + i);
        }
    }
}

public class ThreadDemo03 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable() ;

        Thread t1 = new Thread(myRunnable, "线程1") ;
        Thread t2 = new Thread(myRunnable, "线程2") ;

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

4-三个线程实现窗口卖票的案例(synchronized实现线程同步)

public class SellTickets implements Runnable {
    private static int tickets = 100 ; //初始化票数
    @Override
    public void run() {
        while(true) {
            //synchronized (this) {
            synchronized (SellTickets.class) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(100); //卖票延迟时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在卖第" + tickets + "张票");
                    tickets--;
                }
            }
           // }
        }
    }
}
public class ThreadDemo04 {
    public static void main(String[] args) {
        SellTickets sellTickets = new SellTickets() ;

        Thread t1 = new Thread(sellTickets,"窗口1") ;
        Thread t2 = new Thread(sellTickets, "窗口2") ;
        Thread t3 = new Thread(sellTickets, "窗口3") ;

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

5-Lock锁的方式是实现线程同步

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTickets implements Runnable {
    private static int tickets = 100 ; //初始化票数
    private Lock lock = new ReentrantLock() ;
    @Override
    public void run() {
        while(true) {
            //synchronized (this) {
            //synchronized (SellTickets.class) {
            lock.lock();
                if (tickets > 0) {
                    try {
                        Thread.sleep(100); //卖票延迟时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在卖第" + tickets + "张票");
                    tickets--;
                }
                lock.unlock();
           // }
           // }
        }
    }
}
public class ThreadDemo04 {
    public static void main(String[] args) {
        SellTickets sellTickets = new SellTickets() ;

        Thread t1 = new Thread(sellTickets,"窗口1") ;
        Thread t2 = new Thread(sellTickets, "窗口2") ;
        Thread t3 = new Thread(sellTickets, "窗口3") ;

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

6-生产者与消费者模式案例

牛奶箱类:

public class Box {
    private int milk ;
    private static boolean state = false ;

    public synchronized void put(int milk) throws InterruptedException {
        if(state){ //有牛奶,等待消费者消费
            wait();
        }
        this.milk = milk;
        System.out.println("生产者将第" + this.milk + "瓶牛奶放入箱子中");
        state = true ;
        notifyAll(); //唤醒
    }
    public synchronized void get() throws InterruptedException {
        if(!state){ //没有牛奶,等待生产
            wait();
        }
        System.out.println("消费者从箱子中拿走了第" + this.milk + "瓶牛奶");
        state = false ;
        notifyAll(); //唤醒
    }
}

生产者类:


public class Producer implements Runnable {
    private Box box ;

    public Producer(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        for(int i=1; i<=10; i++){
            try {
                box.put(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

消费者类:

public class Customer implements Runnable {
    private Box box ;

    public Customer(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        while(true){
            try {
                box.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

测试类:

public class BoxDemo {
    public static void main(String[] args) {
        Box box = new Box() ;
        Producer producer = new Producer(box) ;
        Customer customer = new Customer(box) ;

        Thread t1 = new Thread(producer) ;
        Thread t2 = new Thread(customer) ;

        t1.start();
        t2.start();
    }
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nuist__NJUPT

给个鼓励吧,谢谢你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值