线程的应用举例

版权声明: https://blog.csdn.net/if_i_were_a/article/details/82780339

线程的生命周期:新建,就绪,运行,阻塞,死亡

public class Demo01 {

/**

* 线程的生命周期:

*

*/

public static void main(String[] args) {

MyT1 myt1=new MyT1();

Thread t1=new Thread(myt1,"aaa");

Thread t2=new Thread(myt1,"bbb");

for(int i=1;i<1000;i++)

{

if(i==100)

{

t1.start();

t2.start();

}

System.out.println(Thread.currentThread().getName()+"---i="+i);

}

}

static class MyT1 implements Runnable{

@Override

public void run() {

for(int s=0;s<1000;s++)

{

System.out.println(Thread.currentThread().getName()+"----s="+s);

}

}

}

}

创建不断的线程对当前屏幕进行截屏

public class Demo02 extends JFrame {

/**

* 创建不断的线程截屏

*

*/

private boolean isrun=false;

private JButton but=new JButton("start");

private int step=1;

private CaptureScreen sc=null;

public Demo02()

{

super("Demo02");

//组件,弹出来的小方框的宽度和高度

this.setSize(400,300);

this.setLocation(200,200);

this.add(but);

//设置该组件是否为可见的

this.setVisible(true);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//建立一个监听事件

but.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

if(isrun)

{

isrun=false;

sc.interrupt();

but.setText("start");

}

else

{

isrun=true;

sc=new CaptureScreen();

sc.start();

but.setText("stop");

}

}

});

}

class CaptureScreen extends Thread {

Toolkit tool = Toolkit.getDefaultToolkit();

Dimension dim = null;

Robot robot = null;

Rectangle rec = null;

@Override

public void run() {

while (isrun) {

try {

dim = tool.getScreenSize();

robot = new Robot();

//构造一个新的Rectangle,左上角为(0,0),其宽度和高度右

//Dimension参数指定

rec = new Rectangle(dim);

BufferedImage img = robot.createScreenCapture(rec);

System.out.println(img.getRGB(23, 23));

ImageIO.write(img, "jpg", new File("F:\\imag" + (step++) + ".jpg"));

Thread.sleep(300);

} catch (IOException e) {

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

} catch (AWTException e) {

e.printStackTrace();

}

}

}

}

public static void main(String[] args) {

new Demo02();

}

}

猜你喜欢

转载自blog.csdn.net/if_i_were_a/article/details/82780339