File tree Expand file tree Collapse file tree
codes/concurrent/src/main/java/io/github/dunwu/javase/concurrent/thread Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package io .github .dunwu .javase .concurrent .thread ;
2+
3+ import java .io .IOException ;
4+ import java .io .PipedReader ;
5+ import java .io .PipedWriter ;
6+
7+ public class Piped {
8+
9+ public static void main (String [] args ) throws Exception {
10+ PipedWriter out = new PipedWriter ();
11+ PipedReader in = new PipedReader ();
12+ // 将输出流和输入流进行连接,否则在使用时会抛出IOException
13+ out .connect (in );
14+ Thread printThread = new Thread (new Print (in ), "PrintThread" );
15+ printThread .start ();
16+ int receive = 0 ;
17+ try {
18+ while ((receive = System .in .read ()) != -1 ) {
19+ out .write (receive );
20+ }
21+ } finally {
22+ out .close ();
23+ }
24+ }
25+
26+ static class Print implements Runnable {
27+
28+ private PipedReader in ;
29+
30+ Print (PipedReader in ) {
31+ this .in = in ;
32+ }
33+
34+ public void run () {
35+ int receive = 0 ;
36+ try {
37+ while ((receive = in .read ()) != -1 ) {
38+ System .out .print ((char ) receive );
39+ }
40+ } catch (IOException e ) {
41+ e .printStackTrace ();
42+ }
43+ }
44+ }
45+ }
Original file line number Diff line number Diff line change 1+ package io .github .dunwu .javase .concurrent .thread ;
2+
3+ import java .util .concurrent .TimeUnit ;
4+
5+ public class ThreadStopDemo03 {
6+
7+ public static void main (String [] args ) throws Exception {
8+ MyTask one = new MyTask ();
9+ Thread countThread = new Thread (one , "CountThread" );
10+ countThread .start ();
11+ // 睡眠1秒,main线程对CountThread进行中断,使CountThread能够感知中断而结束
12+ TimeUnit .SECONDS .sleep (1 );
13+ countThread .interrupt ();
14+ MyTask two = new MyTask ();
15+ countThread = new Thread (two , "CountThread" );
16+ countThread .start ();
17+ // 睡眠1秒,main线程对Runner two进行取消,使CountThread能够感知on为false而结束
18+ TimeUnit .SECONDS .sleep (1 );
19+ two .cancel ();
20+ }
21+
22+ private static class MyTask implements Runnable {
23+
24+ private long i ;
25+ private volatile boolean on = true ;
26+
27+ @ Override
28+ public void run () {
29+ while (on && !Thread .currentThread ().isInterrupted ()) {
30+ i ++;
31+ }
32+ System .out .println ("Count i = " + i );
33+ }
34+
35+ void cancel () {
36+ on = false ;
37+ }
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments