Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QtThread.java
Go to the documentation of this file.
1// Copyright (C) 2018 BogDan Vatra <bogdan@kdab.com>
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4package org.qtproject.qt.android;
5
6import java.util.ArrayList;
7import java.util.concurrent.Semaphore;
8
9class QtThread {
10 private final ArrayList<Runnable> m_pendingRunnables = new ArrayList<>();
11 private boolean m_exit = false;
12 private final Thread m_qtThread = new Thread(new Runnable() {
13 @Override
14 public void run() {
15 while (!m_exit) {
16 try {
17 ArrayList<Runnable> pendingRunnables;
18 synchronized (m_qtThread) {
19 if (m_pendingRunnables.size() == 0)
20 m_qtThread.wait();
21 pendingRunnables = new ArrayList<>(m_pendingRunnables);
22 m_pendingRunnables.clear();
23 }
24 for (Runnable runnable : pendingRunnables)
25 runnable.run();
26 } catch (InterruptedException e) {
27 e.printStackTrace();
28 }
29 }
30 }
31 });
32
33 QtThread() {
34 m_qtThread.setName("qtMainLoopThread");
35 m_qtThread.start();
36 }
37
38 public void post(final Runnable runnable) {
39 synchronized (m_qtThread) {
40 m_pendingRunnables.add(runnable);
41 m_qtThread.notify();
42 }
43 }
44
45 public void sleep(int milliseconds) {
46 try {
47 m_qtThread.sleep(milliseconds);
48 } catch (InterruptedException e) {
49 e.printStackTrace();
50 }
51 }
52
53 public void run(final Runnable runnable) {
54 final Semaphore sem = new Semaphore(0);
55 synchronized (m_qtThread) {
56 m_pendingRunnables.add(() -> {
57 runnable.run();
58 sem.release();
59 });
60 m_qtThread.notify();
61 }
62 try {
63 sem.acquire();
64 } catch (InterruptedException e) {
65 e.printStackTrace();
66 }
67 }
68
69 public void exit()
70 {
71 m_exit = true;
72 synchronized (m_qtThread) {
73 m_qtThread.notify();
74 }
75 try {
76 m_qtThread.join();
77 } catch (InterruptedException e) {
78 e.printStackTrace();
79 }
80 }
81}
void acquire(int n=1)
Tries to acquire n resources guarded by the semaphore.
void release(int n=1)
Releases n resources guarded by the semaphore.
QSemaphore sem(5)
[0]