By GokiSoft.com| 15:29 26/07/2023|
Java Advanced

Sử dụng MultiThreading sinh ký tự a-zA-Z trong java

Viết chương trình thực hiện yêu cầu sau

- Thread 1 thực hiện sinh ngẫu nhiên các ký tự a-z, cứ 2s thì sinh 1 lần

- Thread 2 thực hiện biến các ký tự thường được sinh ra từ Thread 1 thành ký tự hoa, cứ sau 1s thì thực hiện 1 lần.

Yêu cầu đồng bộ 2 Thread (wait, notify)

- Nếu tổng thời gian xử lý của 2 Thread là 20s thì dựng 2 thread lại.

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

GokiSoft.com [Teacher]
GokiSoft.com

2022-11-18 07:28:58



//Nhap du lieu
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap ten: ");
        String name = scan.nextLine();
        
        //Nhap du lieu khong su dung Scanner
        InputStreamReader reader = new InputStreamReader(System.in);
        
        BufferedReader bReader = new BufferedReader(reader);
        
        System.out.println("Nhap ten: ");
        try {
            name = bReader.readLine();
            
            System.out.println("Hien thi: " + name);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }



Hieu Ngo [community,C2009G]
Hieu Ngo

2021-09-14 06:04:21


#Main.java


public class Main {
    public static void main(String[] args) {
        ThreadOne t1 = new ThreadOne();
        ThreadTwo t2 = new ThreadTwo();

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

    }
}


#ShareData.java


public class ShareData {

    public static final int THREAD_1 = 1;
    public static final int THREAD_2 = 2;

    int currentThread = THREAD_1;
    int rad;
    int  time;

    private static ShareData instance = null;

    public synchronized static ShareData getInstance() {
        if(instance == null) {
            instance = new ShareData();
        }
        return instance;
    }
    public ShareData() {
        time = 0;
    }

    public int getRad() {
        return rad;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }

    public int getCurrentThread() {
        return currentThread;
    }

    public void setCurrentThread(int currentThread) {
        this.currentThread = currentThread;
    }

    public void setRad(int rad) {
        this.rad = rad;
    }
    public synchronized  void plus(int value) {
         time += value;
    }
    public synchronized boolean isALive() {
        return time < 20;
    }
}


#ThreadOne.java


import java.util.Random;

public class ThreadOne extends Thread {
    ShareData shareData;

    public ThreadOne() {
        this.shareData = ShareData.getInstance();
    }



    @Override
    public void run() {
        Random random = new Random();

        while(shareData.isALive()) {
            try {
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (shareData) {
                int a = 97 + random.nextInt(26);
                char c = (char) a;
                shareData.setRad(a);
                System.out.println("Char: "+ c);
                shareData.plus(2);
                shareData.setCurrentThread(ShareData.THREAD_2);
                shareData.notifyAll();
                try {
                    while (shareData.isALive() && shareData.getCurrentThread() != ShareData.THREAD_1) {
                        shareData.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        synchronized (ShareData.getInstance()) {
            shareData.notifyAll();
        }
    }
}


#ThreadTwo.java


public class ThreadTwo extends Thread{
    ShareData shareData;

    public ThreadTwo() {
        this.shareData = ShareData.getInstance();
    }

    @Override
    public void run() {

        while (shareData.isALive()){
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (shareData){
                shareData.notifyAll();
                try {
                    while (shareData.isALive() && shareData.getCurrentThread() != ShareData.THREAD_2) {
                        shareData.wait();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                char characterCase = (char)(shareData.getRad() - 32);
                System.out.println("Char Case: " + characterCase);
                shareData.plus(1);
                shareData.setCurrentThread(ShareData.THREAD_1);

            }
        }
        synchronized (ShareData.getInstance()) {
            shareData.notifyAll();
        }
    }
}



Nguyễn Hùng Anh [community,C2009G]
Nguyễn Hùng Anh

2021-09-14 04:02:00


#Main.java


public class Main {
    public static void main(String [] args) {
        ThreadOne t1 = new ThreadOne();
        ThreadTwo t2 = new ThreadTwo();

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


#SharedData.java


public class SharedData {
    public static final int THREAD_1 = 1;
    public static final int THREAD_2 = 2;

    int rad;
    int time;
    int currentThread = THREAD_1;

    private static SharedData instance = null;

    private SharedData() {
        time = 0;
    }

    public synchronized static SharedData getInstance() {
        if(instance == null) {
            instance = new SharedData();
        }
        return instance;
    }

    public int getRad() {
        return rad;
    }

    public void setRad(int rad) {
        this.rad = rad;
    }

    public int getCurrentThread() {
        return currentThread;
    }

    public void setCurrentThread(int currentThread) {
        this.currentThread = currentThread;
    }

    public boolean isRunning() {
        return time <= 20;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time += time;
    }
}


#ThreadOne.java


import java.util.Random;

public class ThreadOne extends Thread{
    SharedData sharedData;

    public ThreadOne() {
        this.sharedData = SharedData.getInstance();
    }

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Random random = new Random();

        while (sharedData.isRunning()){
            synchronized (sharedData) {
                char c = (char) ('a' + random.nextInt(26));
                System.out.println(c);

                sharedData.setRad(c);
                sharedData.setTime(2);
                sharedData.setCurrentThread(SharedData.THREAD_2);

                sharedData.notifyAll();
                try {
                    while (sharedData.isRunning() && sharedData.getCurrentThread() != SharedData.THREAD_1) {
                        sharedData.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

        System.out.println("T1 stop");
        synchronized (sharedData) {
            sharedData.notifyAll();
        }
    }
}


#ThreadTwo.java


public class ThreadTwo extends Thread{
    SharedData sharedData;

    public ThreadTwo() {
        this.sharedData = SharedData.getInstance();
    }

    @Override
    public void run() {
        while (sharedData.isRunning()){
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (sharedData) {
                sharedData.notifyAll();
                try {
                    while (sharedData.isRunning() && sharedData.getCurrentThread() != SharedData.THREAD_2) {
                        sharedData.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int c = sharedData.getRad();
                System.out.println((char) (c -32));
                sharedData.setTime(1);

                sharedData.setCurrentThread(SharedData.THREAD_1);
            }

        }

        System.out.println("T2 stop");
        synchronized (sharedData) {
            sharedData.notifyAll();
        }
    }
}



hieuvm0512 [community,C2010L]
hieuvm0512

2021-08-22 09:34:13


Main
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.capitalizethread;

/**
 *
 * @author vuive
 */
public class Main {
    public static void main(String[] args){
    Thread1 T1 = new Thread1();
    Thread2 T2 = new Thread2();
    
    T1.start();
    T2.start();
    }
    
}



hieuvm0512 [community,C2010L]
hieuvm0512

2021-08-22 09:34:00


Thread2
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.capitalizethread;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author vuive
 */
public class Thread2 extends Thread {

    @Override
    public void run() {
        ShareData shareData = ShareData.getInstance();
        while (shareData.isLive()) {
            synchronized (shareData) {

                shareData.notifyAll();
                try {
                    while (shareData.isLive() && shareData.getCurrentThread() != ShareData.Thread_2) {
                        shareData.wait();
                    }
                    if (!shareData.isLive()) {
                        break;
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                char c = ShareData.getInstance().getC();
                char d = ShareData.getInstance().Change(c);
                System.out.println("Doi 1s");
                try {
                    Thread2.sleep(1000);

                } catch (InterruptedException ex) {
                    Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                System.out.println(d + "\n");
                shareData.setCurrentThread(ShareData.Thread_1);

            }

        }
        System.out.println("T2 Stop");
        synchronized (shareData) {
            shareData.notifyAll();
        }

    }
}



hieuvm0512 [community,C2010L]
hieuvm0512

2021-08-22 09:33:42


Thread1
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.capitalizethread;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author vuive
 */
public class Thread1 extends Thread {

    @Override
    public void run() {
//        for(int i = 0; i<10;i++){
//        Random r = new Random();
//        System.out.println("Thread1 Start");
//        synchronized(shareData){
//         char c = (char) (r.nextInt(26)+('a'));
//         shareData.setC(c);
//         System.out.println(c);
//        }
//        shareData.notifyAll();
//        shareData.wait();
//        
//        
//        }
        ShareData shareData = ShareData.getInstance();

        for (int i = 0; i < 10; i++) {
                        System.out.println("Doi 2s");
            try {
                Thread1.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }

            synchronized (shareData) {
                Random r = new Random();
                char c = (char) (r.nextInt(26) + ('a'));
                ShareData.getInstance().setC(c);
                System.out.println(c);
                shareData.setCurrentThread(ShareData.Thread_2);
                shareData.notifyAll();
                while (shareData.getCurrentThread() != ShareData.Thread_1) {
                    try {
                        shareData.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
        shareData.setLive(false);
        System.out.println("T1 stop");
        synchronized (shareData) {
            shareData.notifyAll();
        }

    }
}



nguyễn Sử [T2008A]
nguyễn Sử

2021-03-18 10:47:17


//thread_xxx
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MultiThreading;

/**
 *
 * @author WIN10
 */
public class Thread_xxx {

    public Thread_xxx() {
    }
    
    int x;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }
    
    
    
}



nguyễn Sử [T2008A]
nguyễn Sử

2021-03-18 10:46:56

//thread1


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MultiThreading;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author WIN10
 */
public class Thread1 extends Thread {

    Thread_xxx xxx;

    public Thread1(Thread_xxx xxx) {
        this.xxx = xxx;
    }

    @Override
    public void run() {
        try {
            sleep(2000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
        }
        final long start = System.currentTimeMillis();
        Random rad = new Random();
        for (int i = 0; i < 10; i++) {
            synchronized (xxx) {
                int x = rad.nextInt(26) + 97;
                char x1 = (char) (x);
                xxx.setX(x);
                System.out.println("T1 = " + x1);
                long end = 0;
                if ((end - start) >= 2000) {
                    stop();
                    
                    try {
                        xxx.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);

                    }
                    try {
                        sleep(2000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
                        {
                       }
                    }
                    }
                }

            }
        }
    }



nguyễn Sử [T2008A]
nguyễn Sử

2021-03-18 10:46:38


//thread2


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MultiThreading;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author WIN10
 */
public class Thread2 extends Thread {
    Thread_xxx xxx;

    public Thread2(Thread_xxx xxx) {
        this.xxx = xxx;
    }

    public Thread_xxx getXxx() {
        return xxx;
    }

    public void setXxx(Thread_xxx xxx) {
        this.xxx = xxx;
    }
    @Override
    public void run(){
    final long strart = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            synchronized(xxx){
                try {
                    xxx.wait();
                } catch (InterruptedException ex) {
                     Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
                }
                int x = xxx.getX()-32;
                char xxx1 = (char)(x);
                System.out.println("T2= "+xxx1);
                xxx.notifyAll();
                final long end = System.currentTimeMillis();
                long start = 0;
                if ((end - start)>=2000) {
                    stop();
      
                }
                try {
                    sleep(2000);
                } catch (InterruptedException ex) {
                  Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);    
                }
            }
            
        }
    }
    
    
}



nguyễn Sử [T2008A]
nguyễn Sử

2021-03-18 10:45:53


//main


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MultiThreading;

/**
 *
 * @author WIN10
 */
public class Main {
    public static void main(String[] args) {
        Thread_xxx xxx = new Thread_xxx();
        Thread1 t1 = new Thread1(xxx);
        t1.start();
        Thread2 t2 = new Thread2(xxx);
        t2.start();
    }
    
}