今天开始学习java中多线程的实现.
线程是一些可以并行的,独立的执行的代码.之前我编的程序都只能做一件事情,也就是只有一个线程.多线程的编程就是可以将程序任务分成多个并行的子任务,同时运行,互不干扰.我对多线程的理解是从格斗游戏得来的.格斗游戏中两人对打就是通过两个线程来实现的吧,否则如何能够你出你的招,我发我的冲击波呢.
(1月18日)突然想到一个问题,补充一下.多线程是不是我们通常所说的多任务呢?我的理解是,不能这样说也可以这样说.
简单说来,多线程提供了一种在进程内部进行多个线程并行调度的机制,而多任务则提供的是在一个操作系统内部运行多个进程的机制.
多任务操作系统(如windows)的基本原理是这样的:操作系统将cpu的时间片分配给多个线程,每个线程在操作系统指定的时间片内完成(注意,这里的多个线程是分属于不同进程的).操作系统不断的从一个线程的执行切换到另一个线程的执行,如此往复,宏观上看来,就好像是多个线程在一起执行.由于这多个线程分属于不同的进程,因此在我们看来,就好像是多个进程在同时执行,这样就实现了多任务.whoops,真绕口.
如上,多线程和多任务是有很明显的区别的.但是再想一下,在一个应用程序内实现多线程不也是靠cpu分配时间片吗?既然原理是相同的,那么多线程也可以说是多任务的.
一个java程序启动后,就已经有一个线程在运行,我们可以通过下面的例子来初步建立一个线程的实际印象
class testthread{
public static void main(string args[]){
thread t=thread.currentthread();
t.setname("this thread is running");
system.out.println("the running thead:"+t);
try{
for(int i=0;i<5;i++)
{
system.out.println("sleep time"+i);
thread.sleep(1000);//挂起线程,就是让线程休息一会儿,不占用系统资源,因此其它线程可以继续.这里的thread缺省表示主线程
}
}catch(interruptedexception e){system.out.println("thread has wrong");}
}
}public class twothread{
public static void main(string args【】){
new simplethread("helloworld1").start();//创建两个线程的实例,就这么简单
new simplethread("helloworld2").start();
}
}
class simplethread extends thread{ file://真正的内容在这里
public simplethread(string str){
super(str);//super代表simplethread类的直接父类,这里就是thread
}
file://我们要线程做的事情都在这里了
public void run(){
for(int i=0;i<10;i++){
system.out.println(i+" "+getname());
try{
sleep((int)(math.random()*1000));
}catch(interruptedexception e){}
}
system.out.println("done!"+getname());
}
}
class twothread implements runnable{
twothread(){
thread t1=thread.currentthread();
t1.setname("the first main thread");
system.out.println("the running thead:"+t1);
thread t2=new thread(this,"the second thread");//注意这里的this,它表明新线程即t2将会做的事情由this对象来决定,也就是由twothread的run函数来决定
system.out.println("create another thread");
t2.start();//调用该函数将使线程从run函数开始执行
try{
system.out.println("first thread will sleep");
thread.sleep(3000);
}catch(interruptedexception e){system.out.println("first thread has wrong");}
system.out.println("first thread exit");
} public void run()//定义run()函数,在本程序中也就是t2这个新的线程会做的事情
{
try{
for(int i=0;i<5;i++)
{
system.out.println("sleep time for thread 2:"+i);
thread.sleep(1000);
}
}catch(interruptedexception e){system.out.println("thread has wrong");}
system.out.println("second thread exit");
}
public static void main(string args【】){
new twothread();//触发构造函数
}
}
the running rhread:thread[the first main thread,5,main]
creat another thread
first thread will sleep
sleep time for thread 2:0
sleep time for thread 2:1
sleep time for thread 2:2
first thread exit
sleep time for thread 2:3
sleep time for thread 2:4
second thread exit
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器