728x90
더보기
Day20-4. 230525
Ramda식(Ramda Expression)
- JAVA8에서 도입.
-함수형 프로그래밍 개념
-익명함수를 생성하기 위해 간결한 표현방법
- 함수를 할당, 인자로 전달할 수 있다.
- 코드의 가독성 향상, 간결함, 유연성 제공
- 작업스레드 객체생성
public class 작업Thread extends Thread{
@Overide
public void run(){ 스레드실행코드; }
}
Thread thread = new 작업Thread();
- Thread를 익명객체로 작업스레드 객체생성
Thread thread = new Thread(){
public void run(){ 스레드 실행코드; }
}
public class 작업Thread implements Runnable {
@Override
public void run(){ 스레드실행코드; }
}
Thread thread = new Thread(new 작업Thread());
- Runnable인터페이스를 구현한 익명 Thread클래스 객체생성
Thread thread = new Thread(new Runnable(){
@Override
public void run(){ 스레드실행코드; }
}
);
- 람다식으로 구현
(매개변수리스트) -> { 람다식실행코드 }
Thread thread = new Thread( () -> { 스레드실행코드; } );
ex1>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package Ex;
public class Ramda01 {
//Runnable인터페이스를 구현한 익명 Thread클래스 객체생성
//람다식을 사용하지 않고 구현
//thread1은 Runnable인터페이스를 구현한 익명클래스를 생성하여 스레드객체
Thread thread1 = new Thread(new Runnable(){
@Override
public void run(){
System.out.println("출력");
}
}
);
//람다식으로 구현
//thread2은 람다식으로 바로 실행코드를 작성해서 스레드객체생성
Thread thread2 = new Thread(() -> {
System.out.println("출력");
});
}
|
cs |
ex2>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package chap12;
public class BankSystem {
public static void main(String[] args) {
//람다식을 사용
//계좌생성
BankAccount account = new BankAccount(1000);
//입금Thread
Thread depositTh = new Thread(() -> {
account.deposit(800);
});
//출금Thread
Thread withdrawalTh = new Thread(() -> {
account.withdrawl(200);
});
//잔액조회Thread
Thread balanceTh = new Thread(() -> {
int balance = account.getBalance();
System.out.println("현재 잔액 조회:"+balance);
});
depositTh.start();
withdrawalTh.start();
balanceTh.start();
/*람다식을 사용하지 않고 구현
//계좌생성
BankAccount account = new BankAccount(1000);
//입금Thread //account.deposit(800);
Thread depositTh= new Thread(new DepositTask(account));
//출금Thread //account.withdraw(200);
Thread withdrawalTh= new Thread(new WithdrawalTask(account));
//잔액조회Thread-System.out.println(account.getBalance());
Thread balanceTh= new Thread(new BalanceTask(account));
depositTh.start();
withdrawalTh.start();
balanceTh.start();
*/
}
}
|
cs |
람다식으로 구현하면 코드가 간결해짐.
728x90
'개발 수업 > JAVA' 카테고리의 다른 글
[Java] 입출력 스트림/InputStream (0) | 2023.05.26 |
---|---|
[Java] 입출력 스트림(Stream)/바이트 출력 스트림( OutputStream) (0) | 2023.05.25 |
[Java] 스레드 연습 (0) | 2023.05.25 |
[Java] 스레드/스레드 제어,데몬(daemon)스레드 (0) | 2023.05.25 |
[Java] 스레드/멀티 스레드(동기화(synchronized) 메소드) (0) | 2023.05.25 |