编写具有多线程能力的程序经常会用到的方法有:
还有一个重要的关键字:synchronized 【程序编程相关:在red hat linux 10下安装】
run(), start(), wait(), notify(), notifyall(), sleep(), yield(), join() 【推荐阅读:关于JDBC】
一:run() 与start() 【扩展信息:spring,ioc模式与ejb3调用】
本文将对以上内容进行讲解.
示例1:
public class threadtest extends thread {
public void run() { for (int i = 0; i < 10; i++) { system.out.print(" " + i); } }public static void main(string[] args) {
new threadtest().start(); new threadtest().start(); }}这是个简单的多线程程序.run() 与start() 是大家都很熟悉的两个方法.把希望并行处理的代码都放在run() 中;stat() 用于自动调用run(),
这是java的内在机制规定的.并且run() 的访问控制符必须是public,返回值必须是void(这种说法不准确,run() 没有返回值),run() 不带参数.这些规定想必大家都早已知道了,但你是否清楚为什么run方法必须声明成这样的形式?这涉及到java的方法覆盖与重载的规定.这些内容很重要,
请读者参考相关资料.二:关键字synchronized
有了synchronized关键字,多线程程序的运行结果将变得可以控制.synchronized关键字用于保护共享数据.请大家注意 "共享数据",
你一定要分清哪些数据是共享数据,java是面向对象的java/j2me/code/ target=_blank>程序设计语言,所以初学者在编写多线程程序时,容易分不清哪些数据是共享数据.请看下面的例子:示例2:
public class threadtest implements runnable {
public synchronized void run() {
for (int i = 0; i < 10; i++) { system.out.print(" " + i); } }public static void main(string[] args) {
runnable r1 = new threadtest(); runnable r2 = new threadtest(); thread t1 = new thread(r1); thread t2 = new thread(r2); t1.start(); t2.start(); }}在这个程序中,run() 被加上了synchronized关键字.在main方法中创建了两个线程.你可能会认为此程序的运行结果一定为:0123456789
0123456789.但你错了!这个程序中synchronized关键字保护的不是共享数据( 其实在这个程序中synchronized关键字没有起到任何作用,此程序的运行结果是不可预先确定的).这个程序中的t1, t2是两个对象(r1, r2)的线程.java是面向对象的程序设计语言,不同的对象的数据是不同的,r1, r2有各自的run() 方法,而synchronized使同一个对象的多个线程, 在某个时刻只有其中的一个线程可以访问这个对象的synchronized数据.... 下一页