Java Thread Programming 1.3 - Creating and Starting a Thread

Thread.currentThread()
 
public static native Thread currentThread()
to determine which thread is executing a segment of code
 
Many of the methods in Thread are listed with some of the following modifiers: native, final, static, and synchronized. As a quick review, native methods are implemented in non-Java code (typically C or C++ in the JDK). Methods declared to be final may not be overridden in a subclass. When a method is static, it does not pertain to a particular instance of the class, but operates at the class level. The f3 synchronized modifier guarantees that no more than one thread is allowed to execute the statements inside a method at one time. Later in this book, the synchronized modifier is explained in detail.
 
Thread类中有许多方法都有如下的修饰字:
native:方法用非java代码实现,如c、c++
final:被申明为final的方法不能被子类覆盖
static:此方法不要类实例调用,用类名即可调用
synchronized:保证只有同一时间只有一个线程能够执行此方法
 
举例
/*
 * Created on 2005-7-6
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.tju.msnrl.jonathan.thread.chapter1;
 
/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class CurrentThread extends Thread {
    private Thread createThread;
   
    public CurrentThread(){
       this.createThread = Thread.currentThread();
    }
   
    public void run(){
       for(int i = 0; i < 10; i++)
           this.printMsg();
    }
   
    public void printMsg(){
       Thread t = Thread.currentThread();
       if(t == this.createThread){
           System.out.println("create thread");
       }
       else if(t == this){
           System.out.println("currect thread");
       }
       else{
           System.out.println("mystery thread");
       }
    }
 
    public static void main(String[] args) {
       CurrentThread ct = new CurrentThread();
       ct.start();
       for(int i = 0; i < 10; i++)
           ct.printMsg();
    }
}
 
输出结果:
create thread
create thread
create thread
create thread
create thread
create thread
create thread
create thread
create thread
create thread
currect thread
currect thread
currect thread
currect thread
currect thread
currect thread
currect thread
currect thread
currect thread
currect thread
 
getName() / setName()
 
/*
 * Created on 2005-7-6
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.tju.msnrl.jonathan.thread.chapter1;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class GetSetThreadName extends Thread{
    public void run(){
       for(int i = 0; i < 10; i++)
           this.printMsg();
    }  
    public void printMsg(){
       Thread t = Thread.currentThread();
       String threadName = t.getName();
       System.out.println("name = " + threadName);
    }
 
    public static void main(String[] args) {
       GetSetThreadName gstn = new GetSetThreadName();
       gstn.setName("GetSetThreadName");
       gstn.start();
       for(int i = 0; i < 10; i++)
           gstn.printMsg();
    }
}

输出结果:

name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
Threads Started by the JavaVM
JDK 1.2:

main / Finalizer / Reference Handler / Signal dispatcher / AWT-Windows /AWT-EventQueue-0 / SunToolkit.PostEventQueue-0 / Screen Updater

Java虚拟机jdk1.2创建的线程名有:main、Finalizer、Reference Handler、Signal dispatcher、AWT-Windows、AWT-EventQueue-0、SunToolkit.PostEventQueue-0、Screen Updater

Note that the Reference Handler, Signal dispatcher, and SunToolkit.PostEventQueue-0 threads are new to JDK 1.2. The threads named main and Finalizer (Reference Handler and Signal dispatcher for JDK 1.2) are started automatically for every application. The remaining threads are also started by the JavaVM when the application contains any graphical components from AWT or Swing. Therefore, in a JDK 1.2 application with a graphical user interface (GUI), eight threads are automatically started by the JavaVM.

其中:main、Finalizer(jdk1.2以后还包括Reference Handler、Signal dispatcher)是每个应用都会自动创建的,如果应用程序涉及到图形组件AWT/Swing,八个线程都会创建

As mentioned previously, the main thread is responsible for starting application execution by invoking the main() method. This is the thread from which most other developer-defined threads are spawned by application code. The Finalizer thread is used by the JavaVM to execute the finalize() method of objects just before they are garbage collected. The AWT-EventQueue-0 thread is more commonly known as the event thread and invokes event-handling methods such as actionPerformed(), keyPressed(), mouseClicked(), and windowClosing().

各个线程的作用如下:
main:应用程序主线程
Finalizer:是java虚拟机执行finalize()方法进行垃圾收集
AWT-EventQueue-0:事件线程,调用消息相应函数

Although Java requires none of the following, it’s good practice to follow these conventions when naming threads:
1.Invoke setName() on the Thread before start(), and do not rename the Thread after it is started
2.Give each thread a brief, meaningful name when possible.
3.Give each thread a unique name.
4.Do not change the names of JavaVM threads, such as main.

使用setName()函数的推荐用法:
1、在线程start()前调用
2、给线程起个尽可能简洁明了的名字
3、线程名唯一
4、不要改变java虚拟机创建的线程名,比如上面列出的八个

Thread Constructors

核心构造函数如下:
public Thread(ThreadGroup group, Runnable target, String name)
 
ThreadGroup/Thread的关系就像文件夹和文件的关系,文件夹中可以有文件夹和文件,ThreadGroup中可以同时包括ThreadGroup和Thread
target为实现了Runnable接口的类
name为线程名

start() and isAlive()
 
public native synchronized void start()
throws IllegalThreadStateException
 
If the Thread has already been started, an IllegalThreadStateException will be thrown. When the start() method of a Thread is invoked, the new thread is considered to come alive. The thread remains alive until the run() method returns or until the thread is abruptly stopped by the stop() method (which is a deprecated method, as of JDK 1.2!).
 
start()函数必须捕获IllegalThreadStateException异常,因为如果一个线程已经存在,此时再次调用start()则会抛出此异常
 
public final native boolean isAlive()
 
can be used on Thread to test whether a thread has been started and is still running
 
isAlive()判断线程是否开始或正在运行中
 
/*
 * Created on 2005-7-6
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.tju.msnrl.jonathan.thread.chapter1;
 
/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class IsAlive extends Thread {
   
    public void run(){
       for(int i = 0; i < 10; i++)
           this.printMsg();
    }
   
    public void printMsg(){
       Thread t = Thread.currentThread();
       String tName = t.getName();
       System.out.println("name=" + tName);
    }
 
    public static void main(String[] args) {
       IsAlive ia = new IsAlive();
       ia.setName("IsNameTester");
       System.out.println("before start isAlive:" + ia.isAlive());
       ia.start();
       System.out.println("in runing isAlive:" + ia.isAlive());
       for(int i = 0; i < 10; i++)
           ia.printMsg();
       System.out.println("at end of main isAlive:" + ia.isAlive());
    }
   
}

输出结果:

before start isAlive:false
in runing isAlive:true
name=main
name=main
name=main
name=main
name=main
name=main
name=main
name=main
name=main
name=main
at end of main isAlive:true
name=IsNameTester
name=IsNameTester
name=IsNameTester
name=IsNameTester
name=IsNameTester
name=IsNameTester
name=IsNameTester
name=IsNameTester
name=IsNameTester
name=IsNameTester
 
Thread.sleep()
 
Sleeping is a much better option than using a busy loop. A sleeping thread does not use any processor cycles because its execution is suspended for the specified duration.
 
使用sleep而不是true循环,sleep是将线程挂起一定时间
 
The try/catch construct is necessary because while a thread is sleeping, it might be interrupted by another thread. One thread might want to interrupt another to let it know that it should take some sort of action. Later chapters further explore the use of interrupts. Here, it suffices to say that a sleeping thread might be interrupted and will throw an InterruptedException if this occurs.
 
使用sleep时必须捕获InterruptedException异常,因为当进程sleep时,可能被别的进程打断,此时会抛出此异常
 
/*
 * Created on 2005-7-6
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.tju.msnrl.jonathan.thread.chapter1;
 
/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Sleep extends Thread {
   
    public void run(){
       this.loop();
    }
   
    public void loop(){
       Thread t = Thread.currentThread();
       String name = t.getName();
       System.out.println("just enter loop " + name);
      
       for(int i = 0; i < 10; i++){
           try{
              Thread.sleep(200);
           }catch(InterruptedException e){//必须捕获此异常
             
           }
           System.out.println("name =" + name);
       }
      
       System.out.println("be about to leave loop" + name);
    }
 
    public static void main(String[] args) {
       Sleep s = new Sleep();
       s.setName("SleepTester");
       s.start();
       try{
           Thread.sleep(700);
       }catch(InterruptedException e){
          
       }
       s.loop();
    }
}
 
输出结果:

just enter loop SleepTester
name =SleepTester
name =SleepTester
name =SleepTester
just enter loop main
name =SleepTester
name =main
name =SleepTester
name =main
name =SleepTester
name =main
name =SleepTester
name =main
name =SleepTester
name =main
name =SleepTester
name =main
name =SleepTester
be about to leave loopSleepTester
name =main
name =main
name =main
name =main
be about to leave loopmain
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值