多线程编程学习

以下作业,请使用代码实现1-4

  • 线程的生成、运行
  • 线程的优先级、阻塞和信号量
  • 线程池的使用

1、线程的生成


2、线程的优先级


3、线程信号量的处理(阻塞、唤醒等)


4、线程池

import java.util.concurrent.Semaphore;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        Semaphore s = new Semaphore(2);
        //问题1
        Thread1 thread1 = new Thread1();
        thread1.start();
        Thread2 thread2 = new Thread2();
        Thread2 thread3 = new Thread2();
        //问题2
        thread2.setPriority(1);
        thread3.setPriority(2);
        thread2.start();
        thread3.start();
        //问题3
        for (int i = 0; i < 10; i++) {
            new Thread3(s, "Thread*" + i).start();
        }
        //问题4
        ExecutorService examplepool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 14; i++) {
            examplepool.submit(() -> {
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        examplepool.shutdown();
    }
}

import java.lang.*;

public class Thread1 extends Thread{
    @Override
    public void run(){
        System.out.println("Problem1,Thread1 is running.");
    }
}
public class Thread2 extends Thread{
    @Override
    public void run(){
        System.out.println("This thread's priority is :"+this.getPriority());
    }
}
import java.util.concurrent.Semaphore;

public class Thread3 extends Thread {
    Semaphore s;
    String name;
    public Thread3(Semaphore s,String name) {
        this.s = s;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            // 请求资源
            if(s.availablePermits()==0){
                System.out.println("resouce interrupted." + this.name + "is waiting for permits");
            }
            s.acquire();
            System.out.println(this.getName() + " Permited to start.");

            // 模拟对共享资源的访问
            Thread.sleep(1000);

            System.out.println(this.getName() + " releasing the permit.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            s.release();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

YoloMari

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值