框架构建过程中遇到需要用到线程的地方,虽然以前经常听到线程,也看过一些线程类的文章,但真正使用时还是遇到一些问题,此篇正式为了记录自己对线程实操的体会。
入口类代码:
- public class test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub.
- final misc ms = new misc();
- final Thread t1 = new Thread() {
- //public boolean running = false;
- //需要在run方法里调用或定义线程的动作
- public void run() {
- for (int i = 0; i < 100; i++) {
- System.out.println("我是个字符串A" + i);
- }
- ms.callbat("notepad.exe");
- //running = true;
- }
- };
- System.out.println("thread separate......");
- Thread t2 = new Thread() {
- public void run() {
- ms.takescreenshot();
- /* 这里的join方法表示t2要等t1执行完成后才开始执行
- try {
- t1.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }*/
- for (int i = 0; i < 100; i++) {
- System.out.println("我是个字符串B" + i);
- }
- }
- };
- //set thread running priority, its more important if value is larger;这里通过设置优先级让t1先执行,然后不等它执行完成就开始t2的执行
- t1.setPriority(9);
- t2.setPriority(1);
- t1.start();
- t2.start();
- }
- }
misc 类的代码:
- import java.awt.AWTException;
- import java.awt.Rectangle;
- import java.awt.Robot;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- public class misc {
- /**
- * @param args
- */
- public void misc() {
- }
- public void callbat(String batName) {
- String cmd = "cmd /c start D:\\" + batName + ".bat"; // pass
- try {
- Process ps = Runtime.getRuntime().exec(batName);
- ps.waitFor();
- } catch(IOException ioe) {
- ioe.printStackTrace();
- } catch(InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("child thread done......");
- }
- public void takescreenshot() {
- long time = System.currentTimeMillis();
- try {
- Robot robot = new Robot();
- BufferedImage bi = robot.createScreenCapture(new Rectangle(900, 800));
- ImageIO.write(bi, "jpg", new File("D:/screenshot/" + time + ".jpg"));
- } catch(AWTException e) {
- e.printStackTrace();
- } catch(IOException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- misc ms = new misc();
- ms.callbat("notepad.exe");
- ms.takescreenshot();
- }
- }
这里只是线程的非常简单的一个用法,整个线程的知识点还是非常多的,如果需要真正掌握它还真得花一番功夫深入研究才行。这篇文章只是使用线程的一个开始,后续会在基于工作的基础上继续深入研究。
来源: http://www.cnblogs.com/jingwei/p/5838272.html