62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.BufferedReader;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.Channels;
public class InterruptInput {
static BufferedReader in = new BufferedReader(
new InputStreamReader(
Channels.newInputStream(
(new FileInputStream(FileDescriptor.in)).getChannel())));
public static void main(String args[]) {
try {
System.out.println("Enter lines of input (user ctrl+Z Enter to terminate):");
System.out.println("(Input thread will be interrupted in 10 sec.)");
// interrupt input in 10 sec
(new TimeOut()).start();
String line = null;
while ((line = in.readLine()) != null) {
System.out.println("Read line:'"+line+"'");
}
} catch (Exception ex) {
System.out.println(ex.toString()); // printStackTrace();
}
}
public static class TimeOut extends Thread {
int sleepTime = 10000;
Thread threadToInterrupt = null;
public TimeOut() {
// interrupt thread that creates this TimeOut.
threadToInterrupt = Thread.currentThread();
setDaemon(true);
}
public void run() {
try {
sleep(10000); // wait 10 sec
} catch(InterruptedException ex) {/*ignore*/}
threadToInterrupt.interrupt();
}
}
}
# public class AlternateStop extends Object implements Runnable {
# private volatile boolean stopRequested;
# private Thread runThread;
#
# public void run() {
# runThread = Thread.currentThread();
# stopRequested = false;
#
# int count = 0;
#
# while ( !stopRequested ) {
# System.out.println("Running ... count=" + count);
# count++;
#
# try {
# Thread.sleep(300);
# } catch ( InterruptedException x ) {
# Thread.currentThread().interrupt(); // re-assert interrupt
# }
# }
#
# System.out.println("stoped");
# }
#
# public void stopRequest() {
# stopRequested = true;
#
# if ( runThread != null ) {
# runThread.interrupt();
# }
# }
#
# public static void main(String[] args) {
# AlternateStop as = new AlternateStop();
# Thread t = new Thread(as);
# t.start();
#
# try {
# Thread.sleep(2000);
# } catch ( InterruptedException x ) {
# // ignore
# }
#
# as.stopRequest();
# }
# }