分享
 
 
 

Java Thread Programming (1.3) - Creating and Starting a Thread

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有