본문 바로가기

IT일반과목/java

쓰레드-2

객체1-쓰레드n개

객체1개를 공유하는 것이다.

package jongkyu.multithread;


public class MultiThread implements Runnable {

int num=0;

@Override

public void run() {

// TODO Auto-generated method stub

for(int i=0; i<10; i++) {

if(Thread.currentThread().getName().equals("A")) {

System.out.println("====================");

num++;

}

System.out.println("Thread Name : "+Thread.currentThread().getName()+", num : "+num);

try {

Thread.sleep(500);

} catch (Exception e) {

// TODO: handle exception

}

}

}


}


---------------------------------------------------------------------------
package jongkyu.run;

import jongkyu.multithread.MultiThread;

public class Run {
public static void main(String[] args) {
//객체 1개, 스레드n개
MultiThread m = new MultiThread();
//객체 1개를 m으로 만들었다.
Thread thread0 = new Thread(m,"A");//객체1개를 thread0이랑
Thread thread1 = new Thread(m,"B");//객체1개를 thread1이랑 공유할것이다.
thread0.start();
thread1.start();
System.out.println(Thread.currentThread().getName());
System.out.println("MainClass");
}
}

==================================================



===========****************************************************==========================*******************************************=========================

객체 1개, 쓰레드 1개

객체마다 쓰레드가 있는것이다.





package jongkyu.multithread1;


public class MultiThread1 implements Runnable {

int num=0;

@Override

public void run() {

// TODO Auto-generated method stub

for(int i=0; i<10; i++) {

if(Thread.currentThread().getName().equals("A")) {

System.out.println("============");

num++;

}

System.out.println("Thread Name : "+Thread.currentThread().getName() + ", num : "+num);

try {

Thread.sleep(500);

} catch (Exception e) {

// TODO: handle exception

}

}

}


}


-------------------------------------------------------------------------------------------------------

package jongkyu.run;

import jongkyu.multithread1.MultiThread1;

public class Run {
public static void main(String[] args) {
MultiThread1 t0 = new MultiThread1();
MultiThread1 t1 = new MultiThread1();
Thread thread0 = new Thread(t0,"A");
Thread thread1 = new Thread(t1,"B");
thread0.start();
thread1.start();
System.out.println(Thread.currentThread().getName());
System.out.println("MainClass");
}
}

-----------------------------------------------------------------------------------------------




'IT일반과목 > java' 카테고리의 다른 글

자바 콜렉션(수업)-2  (0) 2018.08.06
쓰레드 예제  (0) 2018.08.05
쓰레드-1  (0) 2018.08.05
자바 제너릭 다형성  (0) 2018.08.03
자바 제너릭(Generic)2  (0) 2018.08.03