package test.run;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TestTemplate {
public static void main(final String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("SWT测试模板");
shell.setBounds(800, 100, 400, 300);
shell.open();
final Label lblTest = new Label(shell, SWT.NONE);
lblTest.setText("测试结果:");
lblTest.setBounds(10, 10, 60, 20);
final Text txtTest = new Text(shell, SWT.NONE | SWT.BORDER);
txtTest.setBounds(70, 10, 80, 20);
txtTest.setText("没点击按钮");
final Button btnTest = new Button(shell, SWT.NONE);
btnTest.setText("测试");
btnTest.setBounds(160, 10, 40, 20);
btnTest.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
txtTest.setText("点击了按钮");
printTime();
// 同步是防止一个数据被两人同时用,造成数据的破坏,异步是为了加快程序的运行。
// testAsyncExec();
testSyncExec();
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* 异步asyncExec(同时访问一个资源,提高效率)
*/
protected static void testAsyncExec() {
System.out.println("这里不会因为asyncExec而阻塞,同时进行,就是异步");
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
try {
System.out.println("开始倒计时10秒了");
Thread.sleep(10000);// 倒计时10秒
} catch (final InterruptedException e1) {
}
System.out.println("倒计时10秒完成了");
}
});
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("开始循环5秒");
Thread.sleep(5000);// 循环5秒
System.out.println("循环5秒停止");
} catch (final InterruptedException e) {
}
}
}).start();
}
/**
* 同步syncExec(等待一个线程结束后才开始另一个,保护数据,防止脏读)
*/
protected static void testSyncExec() {
System.out.println("这里因为syncExec阻塞,要等到倒计时完成之后才会运行,就是同步");
Display.getCurrent().syncExec(new Runnable() {
@Override
public void run() {
try {
System.out.println("开始倒计时10秒了");
Thread.sleep(10000);// 倒计时10秒
} catch (final InterruptedException e1) {
}
System.out.println("倒计时10秒完成了");
}
});
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("开始循环5秒");
Thread.sleep(5000);// 循环5秒
System.out.println("循环5秒停止");
} catch (final InterruptedException e) {
}
}
}).start();
}
/**
* 用于计时
*/
protected static void printTime() {
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (i < 16) {
i++;
try {
Thread.sleep(1000);
System.out.println(i + "秒");
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
RCP,SWT,插件开发
【qq群】
336280109
SWT测试模板+同步异步Demo
最新推荐文章于 2021-04-08 19:45:01 发布