java多线程七大编程题(十分受用)

前置须知知识

java多线程的实现方式主要由两种:

  • 一、创建子类继承Thread类,重写run方法
public class ThreadTest02 {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        // 启动线程
        t.start();
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        // 重写run方法
        for(int i = 0; i < 1000; i++){
            System.out.println("线程--->" + i);
        }
    }
}

- 二、实现Runnable接口,重写run方法,但是由于匿名内部类更为灵活,这里基本使用匿名内部类:

不采用匿名内部类:

public class ThreadTest03 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t = new Thread(myRunnable); 
        t.start();
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 100; i++){
            System.out.println("线程--->" + i);
        }
    }
}

采用匿名内部类:

public class ThreadTest04 {
    public static void main(String[] args) {
        // 创建线程对象,采用匿名内部类方式。
        new Thread(new Runnable(){
            @Override
            public void run() {
                for(int i = 0; i < 100; i++){
                    System.out.println("线程---> " + i);
                }
            }
        }).start();
        // 启动线程
    }
}

练习

1. 生产者-消费者

public class PC {
    public static void main(String[] args) {
        Container container = new Container();
        Producer producer = new Producer(container);
        Consumer consumer = new Consumer(container);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}
class Producer implements Runnable{
    private Container container;
    public Producer(Container container){
        this.container=container;
    }
    @Override
    public void run() {
        for (int i=0;i<5;i++){
            try {
                container.set(i);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer implements Runnable{
    private Container container;
    public Consumer(Container container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i=0;i<5;i++){
            try {
                container.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Container{
    private LinkedList<Integer> list = new LinkedList<>();
    private Integer Max_Size = 5;
    public synchronized void set(int val) throws InterruptedException{
        while (true){
            if (list.size()>Max_Size){
                this.wait();
            }else {
                list.add(val);
                System.out.println("生产了"+val);
                this.notify();
                break;
            }
        }
    }
    public synchronized void get() throws InterruptedException {
        while (true){
            if (list.size()==0){
                this.wait();
            }else {
                Integer remove = list.remove();
                System.out.println("消费了"+remove);
                this.notify();
                break;
            }
        }

    }
}

输出结果:

生产了0
消费了0
生产了1
消费了1
生产了2
消费了2
生产了3
消费了3
生产了4
消费了4

2. 倒计时:

public class Time {
    public static void main(String[] args) {
        TimeSub timeSub = new TimeSub();
        new Thread(timeSub).start();
    }
}
class TimeSub implements Runnable{
    private Integer time = 5;
    @Override
    public void run() {
        while (true){
            if (time>0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("倒计时"+time--);
            }else {
                break;
            }
        }
    }
}

输出结果:

倒计时5
倒计时4
倒计时3
倒计时2
倒计时1

3. 艺术表演节目(信号灯法):

public class pw {
    public static void main(String[] args) {
        TV tv = new TV();
        Player player = new Player(tv);
        Watcher watcher = new Watcher(tv);
        new Thread(player).start();
        new Thread(watcher).start();
    }
}
class Player implements Runnable{
    private TV tv;
    public Player(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i=0;i<5;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tv.play("红楼梦");
        }
    }
}
class Watcher implements Runnable{
    private TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i=0;i<5;i++){
            tv.watch();
        }
    }
}
class TV{
    private boolean flag = true;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private String program;
    public void play(String program){
        try {
            lock.lock();
            if (!flag){
                condition.await();
            }
                System.out.println("表演了"+program);
                condition.signal();
                this.program=program;
                this.flag=!flag;
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void watch(){
        try {
            lock.lock();
            if (flag){
                lock.lock();
                condition.await();
            }
                System.out.println("观看了"+program);
                condition.signal();
                this.flag=!flag;
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}

输出结果:

表演了红楼梦
观看了红楼梦
表演了红楼梦
观看了红楼梦
表演了红楼梦
观看了红楼梦
表演了红楼梦
观看了红楼梦
表演了红楼梦
观看了红楼梦

4. 子进程先执行三次,主进程再执行五次,然后这个过程执行三次

public class MainFuc {
    public static void main(String[] args) {
        MainFunctin mainFunctin = new MainFunctin();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<3;i++){
                    mainFunctin.SubFunction();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<3;i++){
                    mainFunctin.MainFunction();
                }
            }
        }).start();

    }
}
class MainFunctin{
    private boolean flag = true;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    public void MainFunction(){
        try {
            lock.lock();
            while (true){
                if (flag){
                    condition.await();
                }else {
                    for (int i=0;i<5;i++){
                        System.out.println("主线程执行"+i);
                    }
                    condition.signal();
                    this.flag=!flag;
                    break;
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void SubFunction(){
        try {
            lock.lock();
            while (true){
                if (!flag){
                    condition.await();
                }else {
                    for (int i =0;i<3;i++){
                        System.out.println("子线程执行"+i);
                    }
                    condition.signal();
                    this.flag=!flag;
                    break;
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

输出结果:

子线程执行0
子线程执行1
子线程执行2
主线程执行0
主线程执行1
主线程执行2
主线程执行3
主线程执行4
子线程执行0
子线程执行1
子线程执行2
主线程执行0
主线程执行1
主线程执行2
主线程执行3
主线程执行4
子线程执行0
子线程执行1
子线程执行2
主线程执行0
主线程执行1
主线程执行2
主线程执行3
主线程执行4

5. 多窗口购票

public class Ticket {
    public static void main(String[] args) {
        Sell sell = new Sell();
        new Thread(sell,"窗口一").start();
        new Thread(sell,"窗口二").start();
        new Thread(sell,"窗口三").start();
    }
}
class Sell implements Runnable{
    private Integer Num = 15;
    Object object = new Object();
    @Override
    public void run() {
            while (true){
                synchronized (object){
                    if (Num>0){
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+"正在售票"+Num--);
                    }else {
                        break;
                    }
                }
        }
    }
}

输出结果:

窗口一正在售票15
窗口三正在售票14
窗口三正在售票13
窗口三正在售票12
窗口三正在售票11
窗口三正在售票10
窗口三正在售票9
窗口三正在售票8
窗口三正在售票7
窗口三正在售票6
窗口二正在售票5
窗口二正在售票4
窗口二正在售票3
窗口二正在售票2
窗口二正在售票1


6. 实现四个线程,两个线程实现对变量i加一,两个对变量i减一

public class FourThread {
    public static void main(String[] args) {
        ThreadFour threadFour = new ThreadFour();
        new Thread(new Runnable() {
            @Override
            public void run() {
                threadFour.add();
            }
        },"线程一").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                threadFour.add();
            }
        },"线程三").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                threadFour.sub();
            }
        },"线程二").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                threadFour.sub();
            }
        },"线程四").start();
    }
}
class ThreadFour{
    private int i = 0;
    public void add(){
        i++;
        System.out.println(Thread.currentThread().getName()+"-->"+i);
    }
    public void sub(){
        i--;
        System.out.println(Thread.currentThread().getName()+"-->"+i);
    }
}

输出结果:

线程一-->1
线程三-->2
线程二-->1
线程四-->0

7.现有三个线程,保证t1,t2,t3的顺序执行

public class ByOrder {
    public static void main(String[] args) throws InterruptedException {
        Order order = new Order();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                order.print();
            }
        },"t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                order.print();
            }
        },"t2");
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                order.print();
            }
        },"t3");
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
        t3.join();
    }
}
class Order {
  public void print(){
      System.out.println("打印"+Thread.currentThread().getName());
  }
}

输出结果:

打印t1
打印t2
打印t3

  • 12
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值