在什么样的程序中,特别需要多线程???
下边的例子中,多线程的优势在哪里??
class SrThread1 //Application的主类
{
public static void main(String args[])
{
SubThread first=new SubThread("first"); //Name is Thread_0
SubThread second=new SubThread("secend"); //Name is Thread_1
first.setPriority(5); //设置优先级为5级
second.setPriority(7); //设置优先级为7级
System.out.println("the priority of first thread is"+first.getPriority());
//输出数据
System.out.println("the Name of first Thread is"+first.getName());
System.out.println("the priority of second Thread is"+second.getPriority());
System.out.println("the Name of second Thread is"+second.getName());
first.start(); //启动线程first
second.start(); //启动线程second
}
}
class SubThread extends Thread //定义Thread 的子类,是用户定义的线程
{
String message;
SubThread (String message)
{
this.message=message;
} //构造方法
public void run()
{
for(int i=0;i<3;i++)
System.out.println(message+"Thread is running"); //是不是这里体现了多线程
try{sleep(100);}
catch(InterruptedException e){return;}
}
}
下边的例子中,多线程的优势在哪里??
class SrThread1 //Application的主类
{
public static void main(String args[])
{
SubThread first=new SubThread("first"); //Name is Thread_0
SubThread second=new SubThread("secend"); //Name is Thread_1
first.setPriority(5); //设置优先级为5级
second.setPriority(7); //设置优先级为7级
System.out.println("the priority of first thread is"+first.getPriority());
//输出数据
System.out.println("the Name of first Thread is"+first.getName());
System.out.println("the priority of second Thread is"+second.getPriority());
System.out.println("the Name of second Thread is"+second.getName());
first.start(); //启动线程first
second.start(); //启动线程second
}
}
class SubThread extends Thread //定义Thread 的子类,是用户定义的线程
{
String message;
SubThread (String message)
{
this.message=message;
} //构造方法
public void run()
{
for(int i=0;i<3;i++)
System.out.println(message+"Thread is running"); //是不是这里体现了多线程
try{sleep(100);}
catch(InterruptedException e){return;}
}
}
楼主【sure2003】截止到2008-07-13 19:19:18的历史汇总数据(不包括此帖):
发帖的总数量:229 发帖的总分数:9893 每贴平均分数:43
回帖的总数量:192 得分贴总数量:4 回帖的得分率:2%
结贴的总数量:227 结贴的总分数:9853
无满意结贴数:2 无满意结贴分:50
未结的帖子数:2 未结的总分数:40
结贴的百分比:99.13 % 结分的百分比:99.60 %
无满意结贴率:0.88 % 无满意结分率:0.51 %
值得尊敬
public static void main (String[] args) {
String temp = "java";
char[] av = new char[2];
for(int i=1; i<temp.length()-1; i++) {
av[i-1] = temp.charAt(i);
}
System.out.println("可以边学"+temp+"边看"+String.valueOf(av));
}
}
你说多线程有什么好处?
网络编程中,服务器端由于需要同时处理多个连接,因此采用多线程同步方式是个不错的选择。所谓多线程同步,指每个线程负责1个连接。每收到1个连接请求,就开辟1个新的线程,进行实际的传输工作。这样,每个线程之间互不影响。当然,采用单线程异步方式也是可以的,只是程序的结构可读性要差些,但优点是线程少,占资源少。
在IO密集的程序中,常采用多线程以充分利用CPU资源。例如word的打印功能,如果只有1个线程,那么在打印机打印期间,我们就不能对该word文档做任何其他操作了,只能坐在那里等他打印完。如果使用多线程,则打印功能只占用1个线程,其他线程负责其他功能,使得CPU和IO设备能够同时得到充分利用。