⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tij315.htm

📁 这也是我们java老师给我们的thinking in java的一些资料
💻 HTM
📖 第 1 页 / 共 5 页
字号:
      <font color=#004488>"Thread[Thread-4,1,main]: 4"</font>,
      <font color=#004488>"Thread[Thread-5,1,main]: 4"</font>,
      <font color=#004488>"Thread[Thread-6,1,main]: 4"</font>,
      <font color=#004488>"Thread[Thread-3,1,main]: 3"</font>,
      <font color=#004488>"Thread[Thread-4,1,main]: 3"</font>,
      <font color=#004488>"Thread[Thread-5,1,main]: 3"</font>,
      <font color=#004488>"Thread[Thread-6,1,main]: 3"</font>,
      <font color=#004488>"Thread[Thread-3,1,main]: 2"</font>,
      <font color=#004488>"Thread[Thread-4,1,main]: 2"</font>,
      <font color=#004488>"Thread[Thread-5,1,main]: 2"</font>,
      <font color=#004488>"Thread[Thread-6,1,main]: 2"</font>,
      <font color=#004488>"Thread[Thread-4,1,main]: 1"</font>,
      <font color=#004488>"Thread[Thread-3,1,main]: 1"</font>,
      <font color=#004488>"Thread[Thread-6,1,main]: 1"</font>,
      <font color=#004488>"Thread[Thread-5,1,main]: 1"</font>
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>In this version, <b>toString(&#160;)</b> is overridden to use <b>Thread.toString(&#160;)</b>, which prints the thread name (which you can set yourself via the constructor; here it&#146;s automatically generated as <b>Thread-1</b>, <b>Thread-2</b>, etc.), the priority level, and the &#147;thread group&#148; that the thread belongs to. Because the threads are self-identifying, there is no <b>threadNumber </b>in this example. The overridden <b>toString(&#160;)</b> also shows the countdown value of the thread. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0180" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>You can see that the priority level of thread 1 is at the highest level, and all the rest of the threads are at the lowest level. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0181" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>Inside <b>run(&#160;)</b>, 100,000 repetitions of a rather expensive floating-point calculation have been added, involving <b>double</b> addition and division. The variable <b>d</b> has been made <b>volatile</b> to ensure that no optimization is performed. Without this calculation, you don&#146;t see the effect of setting the priority levels (try it: comment out the <b>for</b> loop containing the <b>double</b> calculations). With the calculation, you see that thread 1 is given a higher preference by the thread scheduler (at least, this was the behavior on my Windows 2000 machine). Even though printing to the console is also an expensive behavior, you won&#146;t see the priority levels that way, because console printing doesn&#146;t get interrupted (otherwise, the console display would get garbled during threading), whereas the math calculation can be interrupted. The calculation takes long enough that the thread scheduling mechanism jumps in and changes threads, and pays attention to the priorities so that thread 1 gets preference. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0182" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>You can also read the priority of an existing thread with <a name="Index1541"></a><a name="Index1542"></a><b>getPriority(&#160;) </b>and change it at any time (not just in the constructor, as in <b>SimplePriorities.java</b>) with <a name="Index1543"></a><a name="Index1544"></a><b>setPriority(&#160;)</b>.<br></p>
<p>Although the JDK has 10 priority levels, this doesn&#146;t map well to many operating systems. For example, Windows 2000 has 7 priority levels that are not fixed, so the mapping is indeterminate (although Sun&#146;s Solaris has 2<sup>31 </sup>levels). The only portable approach is to stick to <b>MAX_PRIORITY</b>, <b>NORM_PRIORITY</b>, and <b>MIN_PRIORITY</b> when you&#146;re adjusting priority levels. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0173" title="Send BackTalk Comment">Feedback</a></font><br></p>
<h3>
<a name="_Toc375545474"></a><a name="_Toc375545477"></a><a name="_Toc24775841"></a><a name="Heading17107"></a>Daemon
threads<br></h3>
<p><a name="Index1545"></a><a name="Index1546"></a>A &#147;daemon&#148; thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non-daemon threads complete, the program is terminated. Conversely, if there are any non-daemon threads still running, the program doesn&#146;t terminate. There is, for instance, a non-daemon thread that runs <b>main(&#160;)</b>. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap14_2230" title="Send BackTalk Comment">Feedback</a></font><br></p>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c13:SimpleDaemons.java</font>
<font color=#009900>// Daemon threads don't prevent the program from ending.</font>

<font color=#0000ff>public</font> <font color=#0000ff>class</font> SimpleDaemons <font color=#0000ff>extends</font> Thread {
  <font color=#0000ff>public</font> SimpleDaemons() {
    setDaemon(<font color=#0000ff>true</font>); <font color=#009900>// Must be called before start()</font>
    start();
  }
  <font color=#0000ff>public</font> <font color=#0000ff>void</font> run() {
    <font color=#0000ff>while</font>(<font color=#0000ff>true</font>) {
      <font color=#0000ff>try</font> {
        sleep(100);
      } <font color=#0000ff>catch</font> (InterruptedException e) {
        <font color=#0000ff>throw</font> <font color=#0000ff>new</font> RuntimeException(e);
      }
      System.out.println(<font color=#0000ff>this</font>);
    }
  }
  <font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
    <font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i &lt; 10; i++)
      <font color=#0000ff>new</font> SimpleDaemons();
  }
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>You must set the thread to be a daemon by calling <b>setDaemon(&#160;) </b>before it is started. In <b>run(&#160;)</b>, the thread is put to sleep for a little bit. Once the threads are all started, the program terminates immediately, before any threads can print themselves, because there are no non-daemon threads (other than <b>main(&#160;)</b>) holding the program open. Thus, the program terminates without printing any output.<br></p>
<p>You can find out if a thread is a daemon by calling <a name="Index1547"></a><a name="Index1548"></a><b>isDaemon(&#160;)</b>. If a thread is a daemon, then any threads it creates will automatically be daemons, as the following example demonstrates: <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap14_2231" title="Send BackTalk Comment">Feedback</a></font><br></p>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c13:Daemons.java</font>
<font color=#009900>// Daemon threads spawn other daemon threads.</font>
<font color=#0000ff>import</font> java.io.*;
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;

<font color=#0000ff>class</font> Daemon <font color=#0000ff>extends</font> Thread {
  <font color=#0000ff>private</font> Thread[] t = <font color=#0000ff>new</font> Thread[10];
  <font color=#0000ff>public</font> Daemon() {
    setDaemon(<font color=#0000ff>true</font>);
    start();
  }
  <font color=#0000ff>public</font> <font color=#0000ff>void</font> run() {
    <font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i &lt; t.length; i++)
      t[i] = <font color=#0000ff>new</font> DaemonSpawn(i);
    <font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i &lt; t.length; i++)
      System.out.println(<font color=#004488>"t["</font> + i + <font color=#004488>"].isDaemon() = "</font>
        + t[i].isDaemon());
    <font color=#0000ff>while</font>(<font color=#0000ff>true</font>)
      yield();
  }
}

<font color=#0000ff>class</font> DaemonSpawn <font color=#0000ff>extends</font> Thread {
  <font color=#0000ff>public</font> DaemonSpawn(<font color=#0000ff>int</font> i) {
    start();
    System.out.println(<font color=#004488>"DaemonSpawn "</font> + i + <font color=#004488>" started"</font>);
  }
  <font color=#0000ff>public</font> <font color=#0000ff>void</font> run() {
    <font color=#0000ff>while</font>(<font color=#0000ff>true</font>)
      yield();
  }
}

<font color=#0000ff>public</font> <font color=#0000ff>class</font> Daemons {
  <font color=#0000ff>private</font> <font color=#0000ff>static</font> Test monitor = <font color=#0000ff>new</font> Test();
  <font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) <font color=#0000ff>throws</font> Exception {
    Thread d = <font color=#0000ff>new</font> Daemon();
    System.out.println(<font color=#004488>"d.isDaemon() = "</font> + d.isDaemon());
    <font color=#009900>// Allow the daemon threads to</font>
    <font color=#009900>// finish their startup processes:</font>
    Thread.sleep(1000);
    monitor.expect(<font color=#0000ff>new</font> String[] {
      <font color=#004488>"d.isDaemon() = true"</font>,
      <font color=#004488>"DaemonSpawn 0 started"</font>,
      <font color=#004488>"DaemonSpawn 1 started"</font>,
      <font color=#004488>"DaemonSpawn 2 started"</font>,
      <font color=#004488>"DaemonSpawn 3 started"</font>,
      <font color=#004488>"DaemonSpawn 4 started"</font>,
      <font color=#004488>"DaemonSpawn 5 started"</font>,
      <font color=#004488>"DaemonSpawn 6 started"</font>,
      <font color=#004488>"DaemonSpawn 7 started"</font>,
      <font color=#004488>"DaemonSpawn 8 started"</font>,
      <font color=#004488>"DaemonSpawn 9 started"</font>,
      <font color=#004488>"t[0].isDaemon() = true"</font>,
      <font color=#004488>"t[1].isDaemon() = true"</font>,
      <font color=#004488>"t[2].isDaemon() = true"</font>,
      <font color=#004488>"t[3].isDaemon() = true"</font>,
      <font color=#004488>"t[4].isDaemon() = true"</font>,
      <font color=#004488>"t[5].isDaemon() = true"</font>,
      <font color=#004488>"t[6].isDaemon() = true"</font>,
      <font color=#004488>"t[7].isDaemon() = true"</font>,
      <font color=#004488>"t[8].isDaemon() = true"</font>,
      <font color=#004488>"t[9].isDaemon() = true"</font>
    }, Test.IGNORE_ORDER + Test.WAIT);
  }
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>The <b>Daemon</b> thread sets its daemon flag to &#147;true&#148; and then spawns a bunch of other threads&#151;which <i>do not </i>set themselves to daemon mode&#151;to show that they are daemons anyway. Then it goes into an infinite loop that calls <b>yield(&#160;)</b> to give up control to the other processes. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap14_2232" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>There&#146;s nothing to keep the program from terminating once <b>main(&#160;)</b> finishes its job, since there are nothing but daemon threads running. So that you can see the results of starting all the daemon threads, the <b>main(&#160;)</b> thread is put to sleep for a second. Without this, you see only some of the results from the creation of the daemon threads. (Try <b>sleep(&#160;)</b> calls of various lengths to see this behavior.) <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]Chap14_2233" title="Send BackTalk Comment">Feedback</a></font><br></p>
<h3>
<a name="_Toc24775842"></a><a name="Heading17204"></a>Joining a thread</h3>
<p>One thread may call <a name="Index1549"></a><b>join(&#160;)</b> on another thread to wait for the second thread to complete before proceeding. If a thread calls <b>t.join(&#160;) </b>on another thread <b>t</b>, then the calling thread is suspended until the target thread <b>t</b> finishes (when <b>t.isAlive(&#160;)</b> is <b>false</b>).<br></p>
<p>You may also call <b>join(&#160;)</b> with a timeout argument (in either milliseconds or milliseconds and nanoseconds) so that if the target thread doesn&#146;t finish in that period of time, the call to <b>join(&#160;)</b> returns anyway.<br></p>
<p>The call to <b>join(&#160;)</b> may be aborted by calling <a name="Index1550"></a><b>interrupt(&#160;)</b> on the calling thread, so a <b>try-catch</b> clause is required.<br></p>
<p>All of these operations are shown in the following example:<br></p>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c13:Joining.java</font>
<font color=#009900>// Understanding join().</font>
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;

<font color=#0000ff>class</font> Sleeper <font color=#0000ff>extends</font> Thread {
  <font color=#0000ff>private</font> <font color=#0000ff>int</font> duration;
  <font color=#0000ff>public</font> Sleeper(String name, <font color=#0000ff>int</font> sleepTime) {
    <font color=#0000ff>super</font>(name);
    duration = sleepTime;
    start();
  }
  <font color=#0000ff>public</font> <font color=#0000ff>void</font> run() {
    <font color=#0000ff>try</font> {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -