Thread를 상속 받아서 쓰레드를 생성하는 방법
-> java.lang.Thread 클래스를 상속받는다. 그리고 Thread가 가지고 있는 run()메서드를 오버라이딩한다.
Runnable 인터페이스를 구현해서 쓰레드를 만드는 방법
-> Runnable 인터페이스가 가지고 있는 run()메서드를 구현한다
public class MyThread1 extends Thread {
String str;
public MyThread1(String str){
this.str = str;
}
public void run(){
for(int i = 0; i < 10; i ++){
System.out.print(str);
try {
//컴퓨터가 너무 빠르기 때문에 수행결과를 잘 확인 할 수 없어서 Thread.sleep() 메서드를 이용해서 조금씩 쉬었다가 출력할 수 있게한다.
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadExam1 {
public static void main(String[] args) {
// MyThread인스턴스를 2개 만듭니다.
MyThread1 t1 = new MyThread1("*");
MyThread1 t2 = new MyThread1("-");
t1.start();
t2.start();
System.out.print("!!!!!");
}
}
public class MyThread implements Runnable {
String str;
public MyThread(String str){
this.str=str;
}
public void run(){
for(int i=0;i<10;i++){
System.out.println(str);
try {
Thread.sleep((int)(Math.random()*100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadExam {
public static void main(String[] args) {
MyThread t1=new MyThread("*");
MyThread t2=new MyThread("-");
Thread thread1=new Thread(t1);
Thread thread2=new Thread(t2);
thread1.start();
thread2.start();
System.out.println("end");
}
}