当前位置:网站首页>Multithreaded exercises
Multithreaded exercises
2022-06-23 09:40:00 【Linging_ twenty-four】
- Three threads t1、t2、t3. Ensure three threads ,t1 After the execution t2 perform ,t2 After the execution t3 perform .
Use Semaphore
- Three threads t1、t2、t3. Ensure three threads ,t1,t2 After execution ,t3 Re execution .
public class Test01 {
private Object obj = new Object();
// Threads 1、2 After the execution , Reexecution thread 3, Use wait()、notify()
public static void main(String[] args) {
new Test01().exec();
}
public void exec(){
new Thread(()->{
synchronized (obj){
try {
obj.wait();
System.out.println(" Threads :"+Thread.currentThread().getName()+"=> Yes ....");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},String.valueOf(3)).start();
for (int i = 0; i < 2; i++) {
final int tmp = i;
new Thread(()->{
synchronized (obj){
System.out.println(" Threads :" + Thread.currentThread().getName() + "=> Yes ....");
if(tmp == 1)
obj.notify();
}
},String.valueOf(i+1)).start();
}
}
}
public class Test02 {
private CountDownLatch latch =new CountDownLatch(2);
// Threads 1、2 After the execution , Reexecution thread 3, Use CountDownLatch
public static void main(String[] args) {
new Test02().exec();
}
public void exec(){
new Thread(()->{
try {
latch.await();
System.out.println(Thread.currentThread().getName() + "=> Yes ....");
} catch (InterruptedException e) {
e.printStackTrace();
}
}," Threads 3").start();
for (int i = 0; i < 2; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "=> Yes ....");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
},String.valueOf(" Threads " + (i+1))).start();
}
}
}
class T1 implements Runnable{
@Override
public void run() {
System.out.println("1");
}
}
class T2 implements Runnable{
Thread father;
public void set(Thread father) {
this.father = father;
}
@Override
public void run() {
try {
father.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2");
}
}
class T3 implements Runnable{
Thread father;
public void set(Thread father) {
this.father = father;
}
@Override
public void run() {
try {
father.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("3");
}
}
public class Test {
// Use join
public static void main(String[] args) {
T1 task1 = new T1();
T2 task2 = new T2();
T3 task3 = new T3();
Thread t1 = new Thread(task1);
Thread t2 = new Thread(task2);
Thread t3 = new Thread(task3);
task2.set(t1);
task3.set(t1);
t1.start();
t2.start();
t3.start();
}
}
- Existing code simulations have produced 16 Log objects , And it needs to run 16 Seconds to print these logs , Please add 4 Thread to call parseLog() Method to print this separately 16 Log objects , The program just needs to run 4 These log objects can be printed in seconds .
public class Test {
/** * Existing code simulations have produced 16 Log objects , And it needs to run 16 Seconds to print these logs , * Please add 4 Thread to call parseLog() Method to print this separately 16 Log objects , The program just needs to run 4 These log objects can be printed in seconds ; * Ideas 1: * 1. take 16 Log objects are placed in the blocking queue * 2. Turn on 4 Threads get log objects from the blocking queue to execute * 3. The log object execution time is 1s * 4. In this way, the thread will keep running , Blocking * * Ideas 2: * 1. Create a 4 Thread pool of core threads * 2. Add... To the blocking queue 16 Task of printing log objects * 3. Execute the task of thread pool * 4. The log object execution time is 1s * 5. In this way, the thread will be destroyed * */
public static void main(String[] args) {
test01(); // Ideas 1 Realization
//test02(); // Ideas 2 Realization
}
private static void test01() {
long start = System.currentTimeMillis();
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(16);
// take 16 Log objects are placed in the blocking queue
for (int i = 1; i <= 16; i++) {
try {
queue.put(" Log object :" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Turn on 4 Threads get log objects from the blocking queue to execute
for (int i = 0; i < 4; i++) {
new Thread(()->{
while(true){
try {
String log = queue.take();
printLog(log);
long end = System.currentTimeMillis();
System.out.println((end-start) + "ms");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
public static void test02(){
long start = System.currentTimeMillis();
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(16);
// Create a thread pool with four core threads
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
4,
4,
3000,
TimeUnit.MILLISECONDS,
queue,
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
// take 16 The task of printing log objects is put into the blocking queue
for (int i = 0; i < 16; i++) {
final String tmp = " Mission " + (i+1) + "";
poolExecutor.execute(()->{
printLog(tmp);
});
}
poolExecutor.shutdown();
// Determine whether the task of the thread pool has been completed
while(true){
long end = System.currentTimeMillis();
if(poolExecutor.isTerminated()){
System.out.println((end-start) + "ms");
break;
}
}
}
public static void printLog(String log){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "===> Print log =========>" + log);
}
}
- 10 Threads execute synchronously 10 A mission
public class Test2 {
/** * 10 Threads execute synchronously 10 A mission * The way 1:synchronized * The way 2:Lock * The way 3:Semaphore * @param args */
public static void main(String[] args) {
//test01(); //synchronized
//test02(); //Lock
test03(); //Semaphore
}
public static void test01(){
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
// Add tasks to the blocking queue
for (int i = 0; i < 10; i++) {
try {
queue.put(" Mission :" + (i+1));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//10 Threads execute tasks sequentially
for (int i = 0; i < 10; i++) {
new Thread(()->{
synchronized (queue){
try {
String task = queue.take();
executeTask(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
public static void test02(){
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
Lock lock = new ReentrantLock();
// Add tasks to the blocking queue
for (int i = 0; i < 10; i++) {
try {
queue.put(" Mission :" + (i+1));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//10 Threads execute tasks sequentially
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
lock.lock();
String task = queue.take();
executeTask(task);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}).start();
}
}
public static void test03(){
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
Semaphore semaphore = new Semaphore(1);
// Add tasks to the blocking queue
for (int i = 0; i < 10; i++) {
try {
queue.put(" Mission :" + (i+1));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//10 Threads execute tasks sequentially
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
semaphore.acquire();
String task = queue.take();
executeTask(task);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
public static void executeTask(String task){
System.out.println(Thread.currentThread().getName() + "==>" + task);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 10 Items were 20 There are more than one users snapping up , How to make the goods sell normally , Not oversold :
public class Test03 {
//10 A commodity
private int goods = 10;
public static void main(String[] args) {
new Test03().exec();
}
public synchronized void exec(){
for (int i = 0; i < 20; i++) {
new Thread(()->{
if(goods > 0){
System.out.println(Thread.currentThread().getName() + ", Got the first " + goods-- + " Tickets ");
}
},String.valueOf(" user " + (i+1))).start();
}
}
}
- Producer consumer issues
// data
class Data{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
// producer
class Producer implements Runnable{
private Data data;
public Producer(Data data) {
this.data = data;
}
@Override
public void run() {
int i = 0;
while(true) {
synchronized(data){
// If the data is empty , Then the production data
if(data.getMessage() == null) {
data.setMessage(i + "");
System.out.println(" production :" + i);
i++;
}
// Inform consumers of consumption after production data
data.notify();
// Producers hang up
try {
data.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
// consumer
class Consumer implements Runnable{
private Data data;
public Consumer(Data data) {
this.data = data;
}
public void run() {
while(true) {
synchronized(data) {
// If the data is not empty , Consumption
if(data.getMessage() != null) {
System.out.println(" consumption :" + data.getMessage());
data.setMessage(null);
}
// End of consumption , Inform the producer to produce
data.notify();
// Consumers hang up
try {
data.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Test {
public static void main(String[] args) {
Data data = new Data();
Producer p = new Producer(data);
Consumer c = new Consumer(data);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
- Stop threads gracefully
class Task implements Runnable{
private volatile boolean isFlag = true;
public void stop() {
this.isFlag = false;
}
public void run() {
int i = 0;
while(isFlag) {
System.out.println(i++);
}
}
}
public class Test {
// Use flag bits
public static void main(String[] args) throws InterruptedException {
Task task = new Task();
Thread t = new Thread(task);
t.start();
TimeUnit.SECONDS.sleep(1);
task.stop();
}
}
class Task implements Runnable{
public void run() {
int i = 0;
while(true) {
Thread t = Thread.currentThread();
if(t.isInterrupted()) {
// Determine whether it is in an interrupted state
break;
}
System.out.println(i++);
}
}
}
public class Test {
// Use interrupt
public static void main(String[] args) throws InterruptedException {
Task task = new Task();
Thread t = new Thread(task);
t.start();
TimeUnit.SECONDS.sleep(1);
t.interrupt(); // interrupt
}
}
- Multi thread cyclic sequential printing :ABABABABAB, Threads A Print A, Threads B Print B.
Use Object.wait() and notifyAll() perhaps Lock + Condition
- Multi thread cyclic sequential printing :0102030405, Threads 0 Print 0, Threads 1 Print odd numbers , Threads 2 Print even numbers
Use Object.wait() and notifyAll() perhaps Lock + Condition
Subsequent code updates ...
shutdown and shutwdown The difference between :
- shutdown Just set the state of the thread pool to SHUTWDOWN state , The task being carried out will continue to be carried out , If not executed, interrupt .
- shutdownNow Set the status of the thread pool to STOP, The task being performed is stopped , If the task is not executed, it returns .
isShutDown:
- isShutDown When calling shutdown() or shutdownNow() Method, return to true.
- isTerminated When calling shutdown() After the method , And all submitted tasks are returned as true;
- isTerminated When calling shutdownNow() After the method , Returned as after successful stop true;
边栏推荐
猜你喜欢

Web -- Information Disclosure
Redis学习笔记—数据类型:字符串(string)

学习SCI论文绘制技巧(F)

什么是BFC?BFC可以解决什么问题

ICLR 2022 | 视频中的动态卷积TAdaConv以及高效的卷积视频理解模型TAdaConvNeXt

Ionic5 form input box and radio button

Learn SCI thesis drawing skills (f)
![[SUCTF 2019]CheckIn](/img/0e/75bb14e7a3e55ddc5126581a663bfb.png)
[SUCTF 2019]CheckIn
Redis learning notes - slow query analysis

A 32KB cache with direct mapping Memory exercises after class
随机推荐
[GYCTF2020]Blacklist
Redis learning notes RDB of persistence mechanism
#gStore-weekly | gStore源码解析(四):安全机制之黑白名单配置解析
Leetcode topic analysis contains duplicate II
Embedded system overview (learning notes)
cooding代码库的使用笔记
高性能算力中心 — NVMe/NVMe-oF — NVMe-oF Overview
[GYCTF2020]Blacklist
Redis learning notes - slow query analysis
AI系统前沿动态第38期:谷歌已放弃TensorFlow?;训练大模型的四种GPU并行策略;LLVM之父:模块化设计决定AI前途
xml相关面试题
High performance computing center RDMA implementation technology
Mysql database introduction summary
Use Base64 to show pictures
表单重复提交问题
Redis learning notes - geographic information location (GEO)
[MRCTF2020]Ez_bypass
【CTF】 2018_rop
Gstore weekly gstore source code analysis (IV): black and white list configuration analysis of security mechanism
Typora set up image upload service