스레드 구현 두가지 방법
1. Thread 클래스를 확장하고 run()메소드 작성
2. Runnable 인터페이스 구현하고 run()메소드 작성. 그리고 Threaed클래스의 생성자를 통해 객체를 생성해야 한다.
예제11.1 simpleThreadTest
class SimpleThread extends Thread {
public SimpleThread(String name) {
super(name); // 슈퍼클래스 Thread에 저장
}
public void run() {
System.out.println(getName() + " is now running.");
}
}
public class SimpleThreadTest {
public static void main(String[] args) {
SimpleThread t = new SimpleThread("SimpleThread");
System.out.println("Here : 1");
t.start();
System.out.println("Here : 2");
}
}
11.2
public class YieldTest extends Thread {
static boolean doYield; // 다른 스레드로 제어를 양보할 것인가?
static int howOften; // 몇 번 출력할 것인가?
String word;
YieldTest(String whatToSay) {
word = whatToSay;
}
public void run() {
for (int i = 0; i < howOften; i++) {
System.out.println(word);
if (doYield) yield(); // 다른 스레드에게 양보한다.
}
}
public static void main(String[] args) {
howOften = Integer.parseInt(args[1]);
doYield = new Boolean(args[0]).booleanValue();
Thread cur = currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
for (int i = 2; i < args.length; i++)
new YieldTest(args[i]).start();
}
}
11.4
class RunThread extends Thread {
public RunThread(String name) {
super(name);
}
public void run() {
for(int i = 1; i <= 200000; i++) {
if (i % 50000 == 0)
System.out.println("Thread [" + getName() + "] is activated => " + i);
}
}
}
public class SchedulerTest {
private final static int NUM = 2;
public static void main(String[] args) {
Thread[] p = new RunThread[NUM];
p[0] = new RunThread("Pear ");
p[1] = new RunThread("Apple");
p[0].start();
p[1].start();
}
}
11.6
class CircularQueue {
private int contents[], size; // 큐의 내용, 크기
private int head, tail; // head와 tail
private int count; // 큐 내에 있는 원소의 수
public CircularQueue(int sz) {
size = sz;
head = tail = 0;
count = 0;
contents = new int[size];
}
public synchronized int get() {
int res;
while (count == 0)
try { wait();
} catch (InterruptedException e) { }
res = contents[tail];
tail = (tail + 1) % size; // 환형 큐
count--;
notifyAll();
return res;
}
public synchronized void put(int value) {
while ( count == size )
try { wait();
} catch (InterruptedException e) { }
contents[head] = value;
head = (head + 1) % size; // 환형 큐
count++;
notifyAll();
}
}
11.7
class Producer extends Thread {
private CircularQueue boundedBuffer;
private int number;
public Producer(CircularQueue c, int number) {
super("Producer #" + number);
boundedBuffer = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
boundedBuffer.put(i);
System.out.println(getName() + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
11.8
class Consumer extends Thread {
private CircularQueue boundedBuffer;
private int number;
public Consumer(CircularQueue c, int number) {
super("Consumer #" + number);
boundedBuffer = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = boundedBuffer.get();
System.out.println(getName() + " got: " + value);
}
}
}
11.9
public class ProducerConsumerTest {
public static void main(String[] args) {
CircularQueue c = new CircularQueue(1); // 버퍼의 크기는 1로 한정
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
11.10
public class ThreadGrpTree {
public static void main(String[] args) {
ThreadGroup g = Thread.currentThread().getThreadGroup();
ThreadGroup root = g.getParent();
ThreadGroup g1 = new ThreadGroup("g1");
Thread t = new Thread(g1, "x");
root.list();
}
}
11.11
public class ThrGrpMethodTest extends Thread {
ThrGrpMethodTest(ThreadGroup g, String name) {
super(g, name);
}
public void run() {
try {
sleep(100);
System.out.println("Active Thread is " + getName());
} catch (InterruptedException e) {
}
}
public static void main(String[] args) {
ThreadGroup g1 = new ThreadGroup("g1"),
g2 = new ThreadGroup(g1, "g2");
g1.setMaxPriority(Thread.MAX_PRIORITY - 2);
Thread t1 = new ThrGrpMethodTest(g1, "x"),
t2 = new ThrGrpMethodTest(g2, "y"),
t3 = new ThrGrpMethodTest(g2, "z");
t1.setPriority(Thread.MAX_PRIORITY);
t1.start(); t2.start(); t3.start();
g1.list();
Thread[] thrAll = new Thread[g1.activeCount()]; // 3개의 배열 생성
g1.enumerate(thrAll);
for(Thread t : thrAll)
System.out.println(t.toString());
}
}
연습문제 11.6
package quiz_2;
class SimpleThread extends Thread{
public SimpleThread(String name) {
super(name);
}
public void run() {
for(int i=0; i<3; i++) {
System.out.println(i + " " + getName());
try {
sleep ((int)(Math.random ()*1000));
}catch(InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
public class Quiz_11_6 {
public static void main(String[] args) {
new SimpleThread("Seoul").start();
new SimpleThread("Pusan").start();
}
}
연습문제 11.7
package quiz_2;
class MyThread extends Thread{
MyThread(String name){
super(name);
}
public void run() {
while(true) {
System.out.println(getName() + " is now running");
try {
sleep (30);
} catch(InterruptedException e) {
System.out.println("Interrupted is received");
break;
}
} //end while
} //end run()
} //end MyThread
public class Quiz_11_7 {
public static void main(String[] args) {
MyThread t1 = new MyThread("ThreadOne");
MyThread t2 = new MyThread("ThreadTwo");
t1.start();
t2.start();
try {
Thread.sleep (100);
}catch(Exception e) {}
t1.interrupt();
t2.interrupt();
}
}
'전공 과목 이수2👨💻 > JAVA(공)' 카테고리의 다른 글
자바12장 Swing - 예제문제/연습문제 (0) | 2021.08.18 |
---|---|
자바 | 8장 swing연습문제 (0) | 2021.05.27 |
자바 11주차 | 11장 스레드 (0) | 2021.05.19 |
자바10, 11주차 | 9장 예외 (0) | 2021.05.18 |
자바|10주차 인터페이스 (0) | 2021.05.18 |
자바| 1장~6장실습 / 연습문제 (0) | 2021.04.28 |