ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 210826_Thread
    JAVA 2021. 8. 26. 17:05

    (예제1)

    public class Thread_05 {

     

    //클래스를 상속받지 않고 그냥 해보기

     

    String name;

    int num;

     

    public Thread_05(String name,int num) {

    this.name=name;

    this.num=num;

    } 

     

     

    // //방법2

    // @Override

    // public void run(){

    // for(int i=0;i<=num;i++)

    // {

    // System.out.println(name+"==>"+i);

    // }

    // }

     

        //방법1

        public void run() {

     

    for(int i=0;i<=num;i++)

    {

    System.out.println(name+"==>"+i);

    }

    }

     

     

    public static void main(String[] args) {

     

            Thread_05 th1=new Thread_05("one", 300); //300번 반복

            Thread_05 th2=new Thread_05("two", 300);

            Thread_05 th3=new Thread_05("three", 300);

            

            //방법1

            //run()호출

            th1.run();

            th2.run();

            th3.run();

            

            //방법2

     //       th1.start(); //runnable 상태에서 스케줄러에 의해서 하나씩 running상태가 됨

    //        th2.start();

     //      th3.start();

    }

    }

     

    //결과

    one==>0 ~ three==>300 까지 출력됨

     

     

    ~~~~~~~~~~~~~~~~~~~~~~~~~

     

     

    (예제2)

    //Thread_05와 같으나 이번에는 인터페이스 구현해서 해보기

     

    public class Thread_06 implements Runnable{

     

    String name;

    int num;

     

    public Thread_06(String name,int num) {

    this.name=name;

    this.num=num;

    } 

     

    public static void main(String[] args) {

     

    //runnable 인터페이스를 구현한 클래스 생성

    Thread_06 ex1=new Thread_06("one", 300);

    Thread_06 ex2=new Thread_06("two", 300);

    Thread_06 ex3=new Thread_06("three", 300);

     

    //thread 생성해서 인터페이스 구현한 클래스 담아주기

    Thread th1=new Thread(ex1);

    Thread th2=new Thread(ex2);

    Thread th3=new Thread(ex3);

     

    //run메서드 호출

    th1.start();

    th2.start();

    th3.start();

     

    }

     

    @Override

    public void run() {

    // TODO Auto-generated method stub

    for(int i=1;i<=num;i++)

    {

    System.out.println(name+"==>"+i);

    try {

    Thread.sleep(300);  //300은 0.3초

    } catch (InterruptedException e) {

    }

    }

    }

    }

     

     

    //결과

    one==>0 ~ three==>300 까지 0.3초후에 출력됨

     

    'JAVA' 카테고리의 다른 글

    210826_Local IP+Local name  (0) 2021.08.26
    210826_Lamda  (0) 2021.08.26
    210823_Swing(버튼)+image+Arrays  (0) 2021.08.23
    210823_Swing(버튼)+image+Null  (0) 2021.08.23
    210823_Swing(버튼)+image  (0) 2021.08.23

    댓글

Designed by Tistory.