以下作业,请使用代码实现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();
}
}
}