<让我们深入了解一下java线程,以及了解一下为什么需要需要开发基于线程的应用程序>
线程是java语言的一个部分,而且是java的最强大的功能之一。究竟什么是线程,为什么要开发基于线程的应用程序?在本文中,我们将深入了解一下线程的用法,以及使用线程的一些技术。在我们开始讲述线程之前,最好先了解一下有关背景知识和分析一下线程的工作原理。
当程序员一开始开发应用程序时,这些应用程序只能在一个时间内完成一件事情。应用程序从主程序开始执行,直到运行结束,像 fortran/cobol/basic这些语言均是如此。
随着时间的推移,计算机发展到可以在同一时间段内运行不止一个应用程序的时代了,但是应用程序运行时仍然是串行的,即从开始运行到结束,下一条指令接着上一条指令执行。到最近,程序发展到可以在执行时,以若干个线程的形式运行。java就具有运行多线程的能力,可以在同一时间段内进行几个操作,这就意味着给定的操作不必等到另外一个操作结束之后,才能开始。而且对某个操作可以指定更高一级的优先级。
不少程序语言,包括ada, modula-2和c/c++,已经可以提供对线程的支持。同这些语言相比,java的特点是从最底层开始就对线程提供支持。除此以外,标准的java类是可重入的,允许在一个给定的应用程序中由多个线程调用同一方法,而线程彼此之间又互不干扰。java的这些特点为多线程应用程序的设计奠定了基础。
wait(),notify的应用一例
本例子实现了两个线程,每个线程输出1到100的数字。
第一个线程输出1-10,停止,通知第二个线程 输出1-10 第二个线程停止 通知第一个线程 输出11-20 ...
实现的要点是
在java中,每个对象都有个对象锁标志(object lock flag)与之想关联,当一个线程a调用对象的一段synchronized代码时,
它首先要获取与这个对象关联的对象锁标志,然后执行相应的代码,执行结束后,把这个对象锁标志返回给对象;因此,在线程a执行
synchronized代码期间,如果另一个线程b也要执行同一对象的一段synchronized代码时(不一定与线程a执行的相同),它将
要等到线程a执行完后,才能继续....
如何利用wait() notify() notifyall()?
在synchronized代码被执行期间,线程可以调用对象的wait()方法,释放对象锁标志,进入等待状态,并且可以调用notify()或者
notifyall()方法通知正在等待的其他线程。notify()通知等待队列中的第一个线程,notifyall()通知的是等待队列中的所有线程。
package jdeveloper.study;
/**
* title: jdeveloper´s java projdect
* description: n/a
* copyright: copyright (c) 2001
* company: soho http://www.chinajavaworld.com
* @author jdeveloper@21cn.com
* @version 1.0
*/
import java.lang.runnable;
import java.lang.thread;
public class demothread implements runnable{
public demothread() {
testthread testthread1 = new testthread(this,"1");
testthread testthread2 = new testthread(this,"2");
testthread2.start();
testthread1.start();
}
public static void main(string[] args) {
demothread demothread1 = new demothread();
}
public void run(){
testthread t = (testthread) thread.currentthread();
try{
if (!t.getname().equalsignorecase("1")) {
synchronized(this) {
wait();
}
}
while(true){
system.out.println("@time in thread"+ t.getname()+ "="+ t.increasetime());
if(t.gettime()%10 == 0) {
synchronized(this) {
system.out.println("****************************************");
notify();
if ( t.gettime()==100 ) break;
wait();
}
}
}
}catch(exception e){e.printstacktrace();}
}
}
class testthread extends thread{
private int time = 0 ;
public testthread(runnable r,string name){
super(r,name);
}
public int gettime(){
return time;
}
public int increasetime (){
return ++time;
}
}
下载源程序
运行方法 (for windows):
javac -d . demothread.java
java -classpath .;%classpath% jdeveloper.study.demothread
闽公网安备 35060202000074号