반응형

스레드 클래스를 상속받는 클래스를 정의하고 사용해 보자.

 

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
import time
import threading
 
class Worker(threading.Thread):
    def __init__(self, name, count, delay):
        super().__init__()
        self.name = name
        self.count = count
        self.delay = delay
 
    # 스레드 클래스를 상속하는 클래스는 run()를 재정의 해야 한다.
    # 객체를 만들고 start()를 실행하면 run()가 실행된다.
    def run(self):
        print(f"{self.name} job started.")
        for i in range(self.count):
            print(f"{self.name} job: {i}.")
            time.sleep(self.delay)
        print(f"{self.name} job finished.")
 
            
print("Main started.")
 
thread_1 = Worker("First"50.5)
#thread_1.daemon = True
# 데몬 스레드로 설정되면 메인 스레드 종료시 서브 스레드도 종료된다.
thread_1.start()
#thread_1.join()
# join()을 실행한 스레드가 종료할 때까지 나머지 스레드는 대기한다.
 
thread_2 = Worker("Second"50.5)
#thread_2.daemon = True
thread_2.start()
#thread_2.join()
 
print(f"■ Number of threads: {threading.active_count()}")
 
time.sleep(1)
 
print("Main finished.")
 

 

 

 

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
import time
import threading
 
class Worker(threading.Thread):
    def __init__(self, name, count, delay):
        super().__init__()
        self.name = name
        self.count = count
        self.delay = delay
        
    def run(self):
        print(f"{self.name} job started.")
        for i in range(self.count):
            print(f"{self.name} job: {i}.")
            time.sleep(self.delay)
        print(f"{self.name} job finished.")
 
thread_1 = Worker("First"50.5)
thread_2 = Worker("Second"50.5)
thread_3 = Worker("Third"50.5)
threads = [thread_1, thread_2, thread_3]
 
print(f"■ Number of threads: {threading.active_count()}")
# 활성화된 스레드는 메인스레드 뿐이므로 1이 표시된다.
 
for thread in threads:
    thread.start()
    thread.join()
 

 

 

 

thread - Thread-based parallelism

 

반응형
Posted by J-sean
:
반응형

멀티 스레드를 사용해 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import time
import threading
 
def Job(name, count, delay):
    print(f"{name} job started.")
    for i in range(count):
        print(f"{name} job: {i}.")
        time.sleep(delay)
    print(f"{name} job finished.")
 
print("Main started.")
 
thread_1 = threading.Thread(target=Job, args=("First"50.5))
thread_1.start()
 
thread_2 = threading.Thread(target=Job, args=("Second"50.5))
thread_2.start()
 
print(f"■ Number of threads: {threading.active_count()}")
 
time.sleep(1)
 
print("Main finished.")
 

 

 

■ threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

- target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
- args is a list or tuple of arguments for the target invocation. Defaults to ().

 

 

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
import time
import threading
 
def Job(name, count, delay):
    print(f"{name} job started.")
    for i in range(count):
        print(f"{name} job: {i}.")
        time.sleep(delay)
    print(f"{name} job finished.")
 
print("Main started.")
 
thread_1 = threading.Thread(target=Job, args=("First"50.5))
thread_1.daemon = True
thread_1.start()
 
thread_2 = threading.Thread(target=Job, args=("Second"50.5))
thread_2.daemon = True
thread_2.start()
 
print(f"■ Number of threads: {threading.active_count()}")
 
time.sleep(1)
 
print("Main finished.")
 

 

 

 

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
import time
import threading
 
def Job(name, count, delay):
    print(f"{name} job started.")
    for i in range(count):
        print(f"{name} job: {i}.")
        time.sleep(delay)
    print(f"{name} job finished.")
 
print("Main started.")
 
thread_1 = threading.Thread(target=Job, args=("First"50.5))
thread_1.start()
thread_1.join()
 
thread_2 = threading.Thread(target=Job, args=("Second"50.5))
thread_2.start()
thread_2.join()
 
print(f"■ Number of threads: {threading.active_count()}")
 
time.sleep(1)
 
print("Main finished.")
 

 

 

■ join(timeout=None)

- Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
- When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.
- When the timeout argument is not present or None, the operation will block until the thread terminates.
- A thread can be joined many times.

 

 

반응형
Posted by J-sean
:
반응형

It describes how to use the touch API in Android applications.


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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
public class MainActivity extends AppCompatActivity {
 
    int[] id = new int[3];
    int[] x = new int[3];
    int[] y = new int[3];
    String result;
 
    TextView textView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = findViewById(R.id.textView);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
 
        // 3개의 포인터(터치)까지 허용
        int pointer_count = event.getPointerCount();
        if (pointer_count > 3)
            pointer_count = 3;
 
        // ACTION_POINTER_DOWN 과 ACTION_POINTER_UP 이벤트는 액션 값에 추가적인 정보가 인코딩 되어 있다.
        // 액션 값과 MotionEvent.ACTION_POINTER_INDEX_MASK를 & 연산을 하게 되면 눌리거나 떼어진 포인터의 인덱스 값을 알 수 있다.
        // public static final int ACTION_POINTER_INDEX_MASK
        // Bits in the action code that represent a pointer index, used with ACTION_POINTER_DOWN and ACTION_POINTER_UP.
        switch (event.getAction() & MotionEvent.ACTION_MASK)
        {
            case MotionEvent.ACTION_DOWN:
                result = "Single Touch Down:";
                id[0= event.getPointerId(0);
                x[0= (int)event.getX(0);
                y[0= (int)event.getY(0);
                result += "\n(" + x[0+ ", " + y[0+ ")";
                break;
 
            case MotionEvent.ACTION_POINTER_DOWN:
                result = "Multi Touch Down:";
                for (int i = 0; i < pointer_count; i++)
                {
                    id[i] = event.getPointerId(i);
                    x[i] = (int)event.getX(i);
                    y[i] = (int)event.getY(i);
                    result += "\n(" + id[i] + ": " + x[i] + ", " + y[i] + ")";
                }
 
                // Move는 싱글, 멀티 모두 ACTION_MOVE 하나로 처리
            case MotionEvent.ACTION_MOVE:
                result = "Touch Move:";
                for (int i = 0; i < pointer_count; i++)
                {
                    id[i] = event.getPointerId(i);
                    x[i] = (int)event.getX(i);
                    y[i] = (int)event.getY(i);
                    result += "\n(" + id[i] + ": " + x[i] + ", " + y[i] + ")";
                }
                break;
 
            case MotionEvent.ACTION_UP:
                result = "Single Touch Up:";
                id[0= event.getPointerId(0);
                x[0= (int)event.getX(0);
                y[0= (int)event.getY(0);
                result += "\n(" + x[0+ ", " + y[0+ ")";
                break;
 
            case MotionEvent.ACTION_POINTER_UP:
                result = "Multi Touch Up:";
                for (int i = 0; i < pointer_count; i++)
                {
                    id[i] = event.getPointerId(i);
                    x[i] = (int) event.getX(i);
                    y[i] = (int) event.getY(i);
                    result += "\n(" + id[i] + ": " + x[i] + ", " + y[i] + ")";
                }
                break;
 
            default:
                break;
        }
 
        textView.setText(result);
 
        return super.onTouchEvent(event);
    }
}



Run the app and touch the panel.


반응형
Posted by J-sean
: