Java: Solution Concurrency-Thread


Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên

Link bài tập: https://v1study.com/java-cau-hoi-va-bai-tap-phan-concurrency.html

Bài tập 4

package chuabaitap.thread;

import java.util.Random;

class Thread1 extends Thread{
  int rand;
  @Override
  public void run(){
    Random random=new Random();
    do {
      rand = random.nextInt(10000);
    }while (!(1000<=rand && rand<=9999));
  }
}

class Thread2 extends Thread{
  @Override
  public void run(){
    int year=Integer.parseInt(Thread.currentThread().getName());
//    System.out.println(Thread.currentThread().getName());
//    if((year%4==0 && year%100!=0) || year%400==0){
//      System.out.println("Năm "+year+" là năm nhun");
//    }else{
//      System.out.println("Năm "+year+" không là năm nhun");
//    }
    String s="Năm "+year+" là năm ";
    s+=(year%4==0 && year%100!=0 || year%400==0)?"nhun":"thường";
    System.out.println(s);
  }
}

public class BaiTap4 {
  public static void main(String[] args) throws InterruptedException {
    Thread1 t1;
    Thread2 t2;
    while (true) {
      t1 = new Thread1();
      t1.start();
      t1.sleep(2000);
      t2 = new Thread2();
      t2.setName("" + t1.rand);
      t2.start();
    }
  }
}

Bài tập 5

package chuabaitap.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

class T1 extends Thread{
  int rand;
  @Override
  public void run(){
    Random random=new Random();
    rand=random.nextInt(7);
  }
}

class T2 extends Thread{
  @Override
  public void run(){
    System.out.println(Thread.currentThread().getName());
  }
}

public class BaiTap5 {
  public static void main(String[] args) throws InterruptedException {
    Map<String,String> map=new HashMap<>();
    map.put("Monday","Th 2");
    map.put("Tuesday","Th 3");
    map.put("Wednesday","Th 4");
    map.put("Thursday","Th 5");
    map.put("Friday","Th 6");
    map.put("Saturday","Th 7");
    map.put("Sunday","Ch nht");
    T1 t1;
    T2 t2;

    while (true) {
      t1 = new T1();
      t1.start();
      t1.sleep(1000);
      t1.join();
      String key = map.keySet().toArray()[t1.rand].toString();
      System.out.println(key);
      t2 = new T2();
      t2.setName(map.get(key));
      t2.start();
      t2.join();
    }
  }
}
» Tiếp: Solutions I18N
« Trước: Solution câu hỏi và bài tập Collections
Khóa học qua video:
Lập trình Python All Lập trình C# All SQL Server All Lập trình C All Java PHP HTML5-CSS3-JavaScript
Đăng ký Hội viên
Tất cả các video dành cho hội viên
Copied !!!