티스토리에 저장했던 글을 옮겼습니다.
https://mrcocoball.tistory.com/95
class PriorityThread extends Thread {
public void run() {
int sum = 0; // 초기값
Thread t = Thread.currentThread(); // 스레드 참조용 객체 생성
System.out.println(t + "start");
for(int i=0; i<=1000000; i++) {
sum += i;
}
System.out.println(t.getPriority() + "end"); // 스레드 우선순위 가져오기
}
}
public class PriorityTest {
public static void main(String[] args) {
int i;
for(i=Thread.MIN_PRIORITY; i<= Thread.MAX_PRIORITY; i++) {
PriorityThread pt = new PriorityThread(); // 스레드 객체 생성
pt.setPriority(i); // 1~10까지 i 증가시켜서 우선 순위 세트
pt.start();
}
}
}
}
public class JoinTest extends Thread {
int start;
int end;
int total;
public JoinTest(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
int i;
for (i = start; i <= end; i++) {
total += i;
}
}
public static void main(String[] args) {
JoinTest jt1 = new JoinTest(1, 50);
JoinTest jt2 = new JoinTest(51, 100);
jt1.start();
jt2.start();
try{
jt1.join();
jt2.join();
} catch (InterruptedException e) {
System.out.println(e);
}
int lastTotal = jt1.total + jt2.total;
System.out.println("jt1.total = " + jt1.total);
System.out.println("jt2.total = " + jt2.total);
System.out.println("lastTotal = " + lastTotal);
}
}
public class TerminateThread extends Thread {
private boolean flag = false; // flag의 true/false 여부로 종료
int i;
public TerminateThread(String name) {
super(name);
}
public void run() {
while(!flag) { // !flag가 true일 경우 = flag가 false인 경우 반복
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + " end"); // while문 탈출 시 getName() 후 메시지 처리
}
public void setFlag(boolean flag) { // flag를 stop / true 받아서 처리
this.flag = flag;
}
public static void main(String[] args) throws IOException {
TerminateThread threadA = new TerminateThread("A");
TerminateThread threadB = new TerminateThread("B");
TerminateThread threadC = new TerminateThread("C");
threadA.start();
threadB.start();
threadC.start();
int in;
while(true) { // 무한 반복
in = System.in.read(); // 입력값 받음
if (in == 'A') {
threadA.setFlag(true); // A 입력 시 threadA의 flag를 true로 전환
} else if (in == 'B') {
threadB.setFlag(true); // B 입력 시 threadB의 flag를 true로 전환
} else if (in == 'C') {
threadC.setFlag(true); // C 입력 시 threadC의 flag를 true로 전환
} else if (in == 'M') { // M 입력시 모든 thread의 flag를 true로 전환
threadC.setFlag(true);
threadC.setFlag(true);
threadC.setFlag(true);
break; // break로 while문 탈출
} else {
System.out.println("type again");
}
}
System.out.println("main end");
}
}
class Bank {
private int money = 10000;
public void saveMoney(int save) {
synchronized (this) { // 해당 객체를 block
int m = this.getMoney(); // 현재 금액 가져오기
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setMoney( m + save ); // 현재 금액에 save 만큼 저장
}
}
public synchronized void minusMoney(int minus) {
int m = this.getMoney(); // 현재 금액 가져오기
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setMoney ( m - minus ) ; // 현재 금액에 minus 만큼 차감
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
// Rico 스레드
class Rico extends Thread {
public void run() {
System.out.println("리코가 돈을 저축합니다");
SyncMain.myBank.saveMoney(3000);
System.out.println("saveMoney(3000): " + SyncMain.myBank.getMoney() );
}
}
// Mari 스레드
class Mari extends Thread {
public void run() {
System.out.println("마리가 돈을 씁니다");
SyncMain.myBank.minusMoney(1000);
System.out.println("minusMoney(1000): " + SyncMain.myBank.getMoney() );
}
}
public class SyncMain {
public static Bank myBank = new Bank(); // 정적 멤버인 myBank 생성, 공용 리소스
public static void main(String[] args) throws InterruptedException {
Rico r = new Rico();
r.start();
Thread.sleep(200);
Mari m = new Mari();
m.start();
}
}
sychronized(참조형 수식) {
수행문;
}
public void saveMoney(int save) {
synchronized (this) { // 해당 객체를 block
int m = this.getMoney(); // 현재 금액 가져오기
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setMoney( m + save ); // 현재 금액에 save 만큼 저장
}
}
class FastLibrary {
public ArrayList<String> shelf = new ArrayList<String>();
public FastLibrary() {
shelf.add("벽쿵일기 1");
shelf.add("벽쿵일기 2");
shelf.add("벽쿵일기 3");
}
public synchronized String lendBook() throws InterruptedException {
Thread t = Thread.currentThread(); // 현재 스레드 참조
if(shelf.size() == 0) {
System.out.println(t.getName() + "는 책이 없어서 대기합니다");
wait();
System.out.println(t.getName() + "의 대기가 끝났습니다");
}
String book = shelf.remove(0); // shelf의 첫 책을 꺼냄
System.out.println(t.getName() + "가 " + book + "을 빌렸습니다");
return book;
}
public synchronized void returnBook(String book) {
Thread t = Thread.currentThread(); // 현재 스레드 참조
shelf.add(book); // 책을 추가 (입고)
notify(); // notifyAll() 진행
System.out.println(t.getName() + "가 빌린 " + book + " 책이 반환되었습니다");
}
}
class Student extends Thread {
public void run() {
try {
String title = LibraryMain.library.lendBook(); // library 객체에 대해 lendBook() 하여 책 빌리기
if(title==null) return; // title이 없을 경우 = lendBook한 책이 없을 경우 return하여 스레드 종료
sleep(5000);
LibraryMain.library.returnBook(title); // 위의 return을 거치지 않았다면 returnBook 하여 책 반납
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public class LibraryMain {
public static FastLibrary library = new FastLibrary(); // 정적 객체 library 생성, 공용 리소스
public static void main(String[] args) {
Student std1 = new Student();
Student std2 = new Student();
Student std3 = new Student();
Student std4 = new Student();
Student std5 = new Student();
Student std6 = new Student();
std1.start();
std2.start();
std3.start();
std4.start();
std5.start();
std6.start();
}
}
public synchronized void returnBook(String book) {
Thread t = Thread.currentThread(); // 현재 스레드 참조
shelf.add(book); // 책을 추가 (입고)
notifyAll(); // notifyAll() 진행
System.out.println(t.getName() + "가 빌린 " + book + " 책이 반환되었습니다");
}