/**
* <br>
* do what you want to do and never stop it.
* <br>
*/
package com.luch.thread;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutorDemo implements Runnable{
/**
* @param args
*/
public static void main(String[] args) {
SingleThreadExecutorDemo demo = new SingleThreadExecutorDemo();
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(demo);
}
public void run() {
int temp = 0;
int i = 0;
while(true){
int j = new Random().nextInt(100);
System.out.println("temp="+ temp + ",j=" + j + ",i=" + i++ );
try {
if(temp==0 && j > 90){
temp = j/0;
}
Thread.sleep(100);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
temp = 0;
}
}
}
}
* <br>
* do what you want to do and never stop it.
* <br>
*/
package com.luch.thread;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutorDemo implements Runnable{
/**
* @param args
*/
public static void main(String[] args) {
SingleThreadExecutorDemo demo = new SingleThreadExecutorDemo();
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(demo);
}
public void run() {
int temp = 0;
int i = 0;
while(true){
int j = new Random().nextInt(100);
System.out.println("temp="+ temp + ",j=" + j + ",i=" + i++ );
try {
if(temp==0 && j > 90){
temp = j/0;
}
Thread.sleep(100);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
temp = 0;
}
}
}
}
本文通过一个Java示例程序介绍了如何使用单线程执行器(SingleThreadExecutor)。示例中创建了一个无限循环的任务,该任务每100毫秒生成一个0到100之间的随机数并打印出来。如果生成的随机数大于90,则会尝试执行一个会导致运行时异常的操作。
557

被折叠的 条评论
为什么被折叠?



