이제 국비지원 학원을 다닌지 2주가 넘어가고 있다. 자바는 이제 슬슬 마무리 단계이다! 오늘은 자바 마지막 수업에 대해 정리를 해보려한다.
public class PrintThread1 extends Thread {
@Override
public void run() {
for(int i = 0; i < 10; i++){
if(i%2 == 0){
System.out.println("PrintThread1 : " + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class 클래스명 implements Runnable{
public void run(){
// 필수로 구현
// 작업 구간...
Runnable 참조변수명 = new 생성자();
참조변수명.start();
}
}
예제)
public class PrintThread2 implements Runnable {
@Override
public void run() {
for(int i = 0; i < 10; i++){
if(i%2 == 0){
System.out.println("⭐️ PrintThread2 : " + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/*
1,2번 메인
*/
public class Main1 {
public static void main(String[] args) {
Thread th1 = new PrintThread1();
Runnable r1 = new PrintThread2();
Thread th2 = new Thread(r1);
Thread th3 = new Thread(new Runnable() { // 익명클래스
@Override
public void run() {
for(int i = 0; i < 10; i++){
if(i%2 == 0){
System.out.println("🎁 익명 클래스 : " + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread th4 = new Thread(() -> { // 람다식
for(int i = 0; i < 10; i++){
if(i%2 == 0){
System.out.println("✅ 람다를 이용한 익명 클래스 : " + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 메인도 쓰레드이다.
for(int i = 0; i < 10; i++){ // 메인이 먼저 돌고 나머지 메소드들이 실행
if(i%2 == 0){
System.out.println("🐶 메인 : " + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
th1.start();
th2.start();
th3.start();
th4.start();
}
}
Calc calc = (x,y) -> x < y ? x : y;
public class Calc{
public int func1(x,y){
int result = x < y? x : y;
return result;
}
}
예제)
interface Compare{
public int compartTo(int a, int b);
}
public class Lambda2 {
public static void exec(Compare com){
int num1 = 10;
int num2 = 20;
int result = com.compartTo(num1, num2);
System.out.println(result);
}
public static void main(String[] args) {
exec((i, j) -> {
return i + j;
});
exec((i, j) -> {
return i * j;
});
}
}
ATM기를 이용하여 출금되는 프로그램을 만들어보자.
ATM.java
public class ATM implements Runnable{
private int money = 1000000;
// 메소드 동기화
public synchronized void withdraw(int money){ // 출금
this.money -= money;
System.out.println(Thread.currentThread().getName() + "가" + money + "원 출금 ✅"); // 현재 쓰레드의 이름
System.out.println("잔액 : " + this.money + "원");
}
@Override
public void run() {
// synchronized (this){
for(int i =0; i < 10; i++){
withdraw(10000);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// }
}
}
Main.java
public class Main3 {
public static void main(String[] args) {
ATM kbbank = new ATM();
Thread apple = new Thread(kbbank, "김사과");
Thread banana = new Thread(kbbank, "반하나"); // 쓰레드 객체 생성
apple.start();
banana.start();
}
}