티스토리 뷰
1. 프로세스와 쓰레드의 차이점은?
프로세스는 메모리에 올라가 있는 실행 중인 프로그램을 말한다.
쓰레드는 일종의 프로그램 중 하나로 프로그램 안의 또 다른 프로그램을 말한다.
2. 쓰레드에서 동기화란 무엇인가?
단일 프로세스에서는 발생하지 않는 문제로 하나의 인스턴스를 여러 쓰레드가 공유하게 되면서 생기는 문제이다.
이 문제를 해결하기 위해 한 번에 하나의 쓰레드만 객체에 접근할 수 있도록 객체에 락을 걸어서 데이터의 일관성을 유지하는 것.
class Account{
int balance = 200; // 잔액
// 출금
public synchronized void withdraw(int money) {
if(balance >= money) {
String threadName = Thread.currentThread().getName();
try {
System.out.println(threadName + ", 슬립전: " + balance);
Thread.sleep(1000); // checked exception이기 때문에 반드시 예외처리!
} catch (Exception e) {
e.printStackTrace();
}
threadName = Thread.currentThread().getName();
System.out.println(threadName + ", 빼기 전: " + balance);
balance -= money;
threadName = Thread.currentThread().getName();
System.out.println(threadName + ", 빼기후 : " + balance);
}
}
}
class AccountTread implements Runnable{
Account acc = new Account();
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ", balance: " + acc.balance);
while(acc.balance > 0) {
int money = 200;
acc.withdraw(money); // balance에서 money 값 빼줌
threadName = Thread.currentThread().getName();
System.out.println(threadName + ", 잔액: " + acc.balance);
}
}
}
public class SyncTest {
public static void main(String[] args) {
// 쓰레드 이름 확인 방법
String threadName = Thread.currentThread().getName();
System.out.println(threadName);
// 잔액 200원 메모리에 올라감.
Runnable r = new AccountTread(); // 폴리몰티즘 적용
/*
Thread t1 = new Thread(r); // run() 함수 실행을 요청하기 위한 객체 생성.
// thread는 run() 함수 실행을 요청하기 때문에 무조건 run함수가 있어야한다.
Thread t2 = new Thread(r);
t1.start();
t2.start();
*/
Thread t1 = new Thread(r, "첫번째"); // 이름을 정해준다.
Thread t2 = new Thread(r, "두번째");
t1.start();
t2.start();
}
}
// 출력 값이 0과 -200이 랜덤으로 출력된다.
// 0값 출력을 원했는데... -200이 출력되다니... 분명 balance 값이 0보다 클때 조건을 설정했는데..
// public synchronized void withdraw(int money)
// synchronized를 붙이면 해결!!
// 쓰레드는 디버깅 해봐도 과정을 확인하기 어렵다.
/*
출력은 둘중 하나, 뭐가 먼저 나올지는 전적으로 OS에게 달렸기 때문에 알수 없다.
main
첫번째, balance: 200
두번째, balance: 200
첫번째, 슬립전: 200
첫번째, 빼기 전: 200
첫번째, 빼기후 : 0
첫번째, 잔액: 0
두번째, 잔액: 0
두번째, balance: 200
두번째, 슬립전: 200
첫번째, balance: 200
두번째, 빼기 전: 200
두번째, 빼기후 : 0
두번째, 잔액: 0
첫번째, 잔액: 0
*/
하나의 인스턴스( Runnable r = new AccountTread(); 에 있는 balance 값?)를 여러 쓰레드가 공유하게 되면 문제가 발생한다.(-200출력)
그래서 공유가 되지 않도록 하는 것이 synchronized 이다.
위에서 balance 값을 공유하는 부분이 Account 함수 부분이기 때문에 withdraw에 synchronized를 붙이게 되면
해당 함수가 실행될 때 여러 쓰레드가 동시에 접근할 수 없게 된다.
원래는 방(인스턴스)에 접근할 수 있는 문이 여러개 있어서 아무나(여러 쓰레드) 동시에 들어갈 수 있었는데 synchronized를 해줌으로써 문을 하나만 열어 놓고 한명씩만 순차적으로 접근 할 수 있게 막는 것이다. 대신 누가 먼저 들어갈지는 OS가 내부적으로 정해진 알고리즘에 따라 결정하기 때문에 누가 먼저 들어갈지는 정확히 알 수 없다.
3.html 에서 display 종류와 속성에 대하여 설명하시오.
display 태그는 요소를 어떻게 보여줄지를 결정하는 속성이다.
- none : 화면에 나타나지 않는다.( 화면에 출력되지 않는다)
- block : 블록태그 특징과 같다. 한줄을 다 차지한다.
- inline : 인라인 태그 특징과 같다. 크기 값을 지정해도 변화가 없다!!!(width, height, margin, padding 값 지정 불가!)
- inline-block : 인라인 태그의 특징을 갖지만 크기 값(width, height, margin, padding 값)을 지정해 줄 수 있다.
코드펜이 이상하네....
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<style>
div{
width:100px;
height:100px;
font-weight:bold;
text-align:center;
}
body div:nth-child(1) {
background-color:#ff0000;
color:#ffffff;
}
body div:nth-child(2) {
background-color:#00ff00;
color:#ffffff;
visibility: hidden;
}
body div:nth-child(3) {
background-color:#0000ff;
color:#ffffff;
}
body div:nth-child(4) {
background-color: orange;
color:#ffffff;
}
body div:nth-child(5) {
background-color:#a14e96;
color:#ffffff;
display: inline;
}
body div:nth-child(6) {
background-color:black;
color:#ffffff;
display: inline;
}
body div:nth-child(7) {
background-color: hotpink;
color:#ffffff;
display: none;
}
body div:nth-child(8) {
background-color:#4d7436;
color:#ffffff;
display: inline;
}
body div:nth-child(9) {
background-color: rgb(153, 153, 153);
color:#ffffff;
display: inline-block;
}
</style>
</head>
<body>
<div>content1</div>
<div>content2</div>
<div>content3</div>
<div>content4</div>
<div>content5</div>
<div>content6</div>
<div>content7</div>
<div>content8</div>
<div>content9</div>
</body>
</html>
출력
4.px 과 em 의 차이는? (font)
- px(상대적 크기) : 모니터 크기에 따라 달라진다.( 그래서 모니터가 커진 상태에서 해상도가 작으면 px(점) 크기가 커지기 때문에 화질이 나쁘다).
- em : 웹 브라우저가 기본으로 가지고 있는 단위는 1em(디폴트 크기) = 16px
5. inline-block 태그의 종류는?
buttion : 클릭할 수 있는 버튼을 표시
select : 드롭다운 메뉴(아래로 펼쳐지는 목록상자)
6. display:none; 과 visibility:hidden;의 차이는?
display : none 은 아예 없어지지만(출력 자체가 안됨), visibilty: hidden은 화면에 출력되서 공간은 남겨두지만 보이지는 않는다(투명인간으로 생각해보자......)
3번 문제의 content2( body div:nth-child(2) ) 와 content7( body div:nth-child(7) )을 보면 잘 나타나 있다.
7.HashMap<Integer, String> map = new HashMap<>();
map.put(45, "Brown");
map.put(37, "James");
map.put(23, "Martin");
======================================
위의 Value 값이 다나오도록 for 문 돌리시오.
import java.util.HashMap;
import java.util.Set;
public class HashMapValuePrac {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(45, "Brown");
map.put(37, "James");
map.put(23, "Martin");
Set<Integer> set = map.keySet();
for (Integer n : set) {
System.out.println("key: " + n + '\t' + "value: " + map.get(n));
}
}
}
//출력
//key: 37 value: James
//key: 23 value: Martin
//key: 45 value: Brown
→ Iterator는 List, Set계열에 구현(Map은 없음)
8.로또 번호6개를 출력 -중복없이
Set 으로 구현 과 일반 for 문 구현을 따로 하시오.
Set으로 구현
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetRottoTest {
public static void main(String[] args) {
final int ROTTO_NUM = 6;
Set<Integer> set = new HashSet<>();
for(int i = 0; i < ROTTO_NUM; i++) {
set.add((int)(Math.random() * 45 + 1));
}
for (Iterator itr = set.iterator(); itr.hasNext();) {
System.out.print(itr.next() + "\t");
}
}
}
for문 구현
public class ForRottoTest {
public static void main(String[] args) {
int[] num = new int[6];
for(int i = 0; i < 6; i++) {
num[i] = (int)(Math.random() * 45 + 1);
for(int j = 0; j < i; j++) {
if(num[i] == num[j]) {
i--;
}
}
}
for (int i : num) {
System.out.print(i + " ");
}
}
}
9.아래가 돌아 가도록 구현하시오.
main(){
ThreadCount threadCount = new ThreadCount();
threadCount.start();
String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
System.out.println("입력하신 값은 " + input + "입니다.");
}
=============================================
10 9 8 7 6 ... 이 1초마다 실행 되도록 쓰레드를 완성하시오.
import javax.swing.JOptionPane;
class ThreadCount extends Thread {
public void run() {
for (int i = 10; i > 0; i--) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
} // for
}
}
public class ThreadTest {
public static void main(String[] args) {
ThreadCount threadCount = new ThreadCount();
threadCount.start();
String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
System.out.println("입력하신 값은 " + input + "입니다.");
}
}
메뉴 만들기
See the Pen menu by SE (@whaletree) on CodePen.
'수업문제' 카테고리의 다른 글
[문제] 11월 15일 (채팅 프로그램, 미디어 쿼리, 반응형 웹) (0) | 2021.11.15 |
---|---|
[문제] 11월 12일 (I/O스트림, 입출력, float, position) (0) | 2021.11.13 |
[문제] 11월 10일 (Map, Stack, Queue) (0) | 2021.11.11 |
[문제] 11월 9일 (HashSet, hashcode, ThreeSet ) (0) | 2021.11.10 |
- Total
- Today
- Yesterday
- 사칙연산 계산기
- Session
- JSP
- el
- 래퍼 클래스
- 제네릭
- hashset
- Generic
- object
- string
- 채팅
- equals
- compareTo
- toString
- 프로토콜
- SOCKET
- 쿠키
- TreeSet
- exception
- abstract
- 진척도 70번
- 세션
- 입출력
- Request
- response
- Servlet
- 쓰레드
- 부트스트랩
- 참조형
- 예외처리
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |