[Java] Thread 예제
- BACKEND/Java
- 2017. 11. 2. 16:11
package Thread;
class ThreadDemo extends Thread{ //실제 작업, 스레드를 상속받아서 스레드가 된다.
//private String name;
// public ThreadDemo(String name) {
// this.name = name;
// super(name);
// }
@Override
public void run() { // 자식 스레드가 해야할 일을 적어주는 곳
int sum = 0;
for(int i=0; i<5; i++) {
try {
sleep(500); //오버라이드 규칙으로 인해 throws말고 try/catch를 사용해야함
//시분할 작업, 프로그램 속도 제어
} catch (InterruptedException e) {
e.printStackTrace();
}
sum += i;
System.out.println(getName()+":"+sum);
}
}
}
public class ThreadTest1 {
public static void main(String[] args) { //메인스레드
//ThreadDemo demo1 = new ThreadDemo("first");
// 위에서 스레드를 상속받았으니 인스턴스가 스레드가 된다.
//ThreadDemo demo2 = new ThreadDemo("second"); // 자식스레드
ThreadDemo demo1 = new ThreadDemo();
ThreadDemo demo2 = new ThreadDemo();
demo1.start();
demo2.start();
}
}
package Thread;
class ThreadDemo1 implements Runnable{
@Override
public void run() { //call back 메소드, Thread만 호출 가능
int sum = 0;
for(int i=0; i<5; i++) {
try {
Thread.sleep(500); //document로 찾았을때 static은 인스턴스 없이 사용가능
} catch (InterruptedException e) {
e.printStackTrace();
}
sum += i;
System.out.println(Thread.currentThread().getName()+":"+sum);
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
ThreadDemo1 demo1 = new ThreadDemo1();
ThreadDemo1 demo2 = new ThreadDemo1();
Thread t1 = new Thread(demo1); //인터페이스인 Runnable->Thread로 포장
Thread t2 = new Thread(demo2);
t1.start();
t2.start();
}
}
package Thread;
class ThreadDemo2 extends Thread{
String name;
public ThreadDemo2(String name) {
super(name);
}
@Override
public void run() {
System.out.println(getName()+"자식 스레드 시작");
int cnt = 0;
do {
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
cnt++;
System.out.println(getName()+":"+cnt);
}while(cnt<10);
System.out.println("자식 스레드 종료");
}
}
public class ThreadTest3 {
public static void main(String[] args) {
System.out.println("메인 스레드 시작");
ThreadDemo2 demo1 = new ThreadDemo2("first");
ThreadDemo2 demo2 = new ThreadDemo2("second");
demo1.start();
demo2.start();
int cnt = 0;
do {
try {
Thread.sleep(200);
}catch(InterruptedException e) {
e.printStackTrace();
}
cnt++;
System.out.println(".");
}while(cnt<10);
System.out.println("메인 스레드 종료");
}
}
package Thread;
//ThreadTest3을 Thread -> Runnable로 바꾸기
class ThreadDemo3 implements Runnable{
String name;
ThreadDemo3(String name){
this.name = name;
}
@Override
public void run() {
System.out.println(name+"자식 스레드 시작");
int cnt = 0;
do {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
cnt++;
System.out.println(name+":"+cnt);
}while(cnt<10);
System.out.println("자식 스레드 종료");
}
}
public class ThreadTest4{
public static void main(String[] args) {
System.out.println("메인 스레드 시작");
ThreadDemo2 demo1 = new ThreadDemo2("first");
ThreadDemo2 demo2 = new ThreadDemo2("second");
Thread t1 = new Thread(demo1);
Thread t2 = new Thread(demo2);
t1.start();
t2.start();
int cnt = 0;
do {
try {
Thread.sleep(200);
}catch(InterruptedException e) {
e.printStackTrace();
}
cnt++;
System.out.println(".");
}while(cnt<10);
System.out.println("메인 스레드 종료");
}
}
package Thread;
class ThreadDemo4 implements Runnable{
String name;
// Thread t;
ThreadDemo4(String n){
name=n;
// t = new Thread(this);
// t.start();
new Thread(this).start();
}
@Override
public void run() {
for(int i=0; i<5;i++) {
System.out.println(name+":"+i);
}
}
}
public class ThreadTest5 {
public static void main(String[] args) {
ThreadDemo4 d1 = new ThreadDemo4("스레드1");
ThreadDemo4 d2 = new ThreadDemo4("스레드2");
ThreadDemo4 d3 = new ThreadDemo4("스레드3");
}
}
<Syncronized 예제>
package Thread;
class Toilet{
public synchronized static void openDoor(String name) {
System.out.println(name + "입장");
for(int i=0; i<100000; i++) {
if(i == 5000) {
System.out.println(name+"끄응~~~!!");
}
}
System.out.println(name+"퇴장");
}
}
class Family extends Thread{
Toilet toilet;
String who;
Family(Toilet t, String w){
toilet = t;
who = w;
}
@Override
public void run() {
toilet.openDoor(who);
}
}
public class SyncTest1 {
public static void main(String[] args) {
Toilet t = new Toilet();
Family father = new Family(t, "아버지");
Family mother = new Family(t, "어머니");
Family brother = new Family(t, "형");
Family sister = new Family(t, "누나");
Family me = new Family(t, "나");
mother.start();
brother.start();
sister.start();
me.start();
}
}
package Thread;
import java.util.Stack;
//자판기 예제
class AutoMachine{ //자판기
Stack store = new Stack(); // Stack -> 넣을때는 : Push() 꺼내올때는 : POP()
synchronized void putDrink(String drink) {
store.push(drink);
notify(); //wait()로 쉬게한 Thread를 실행시키는 메소드
}
synchronized String getDrink() {
while(store.isEmpty()) //저장소가 비어있는 동안 기다리기
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return store.pop().toString();
}
}
class Producer implements Runnable{ //공급자
private AutoMachine auto;
Producer(AutoMachine a){
auto=a;
}
@Override
public void run() {
for(int i=0; i<10; i++) {
System.out.println(Thread.currentThread().getName()+": 음료수 No."+ i + "채워 넣음");
auto.putDrink("음료수 No."+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{ //고객
private AutoMachine auto;
Consumer(AutoMachine a){
auto = a;
}
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+auto.getDrink()+"꺼내 먹음");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class SyncTest2 {
public static void main(String[] args) {
AutoMachine auto = new AutoMachine();
Producer hong = new Producer(auto);
Consumer kim = new Consumer(auto);
Thread h = new Thread(hong, "홍길동");
Thread k = new Thread(kim, "김유신");
h.start();
k.start();
}
}
'BACKEND > Java' 카테고리의 다른 글
[Java] Window Programming (0) | 2017.11.06 |
---|---|
[Java] IO 예제 (0) | 2017.11.02 |
[Java] Thread (0) | 2017.11.01 |
[Java] IO (0) | 2017.10.30 |
[Java] Exception (0) | 2017.10.30 |