多语言展示
当前在线:958今日阅读:91今日分享:37

java中线程的问题,及其实例

线程是进程的微量单位,一个进程中至少有一个线程,线程消耗的资源比线程要少很多,一般、  50个线程消耗的资源才等于一个进程 。{性能测试软件  LoadRunner  HP}
工具/原料

eclipse、

方法/步骤
1

第一种方式   继承Thread 类  第二种方式   实现Runnable 接口      main方法也是由一个线程执行,这个线程叫主线程;  main{   m1{};   m2();   m3();  }   使用Runnable接口实现线程的好处  使用Runnable接口实现线程的好处  1.解除线程与线程功能的耦合     2.保留类的继承特性

2

public class ThreadDemo { public static void main(String[] args) {父类的引用指向子类的对象  Thread t=new MyThread();  Thread t1=new MyThread1();  //启动 线程  t.start();  t1.start(); }}//继承Thread类创建线程class MyThread extends Thread{ //线程要做的内容 public void run() {  for(int i=0;i<100;i++){

3

System.out.println('你是谁?'+i);  } }}class MyThread1 extends Thread{ //线程要做的内容 public void run() {  for(int i=0;i<100;i++){   System.out.println('查水表?'+i);  } }}

4

public class ThreadDemo2 { public static void main(String[] args) {  Runnable r1=new MyRunnable1();  Runnable r2=new MyRunnable2();  Thread t1=new Thread(r1);  Thread t2=new Thread(r2);  t1.start();  t2.start(); }}class MyRunnable1 implements Runnable{ public void run() {  for(int i=0;i<10;i++) {   System.out.println('你是谁啊?');  } }}class MyRunnable2 implements Runnable{ public void run() {  for(int i=0;i<10;i++) {   System.out.println('开门查水表?');  } }}

5

public class ThreadDemo3 { public static void main(String[] args) {  ExecutorService es=Executors.newFixedThreadPool(3);  Runnable r1=new Runnable(){   public void run() {   System.out.println('hello!');   }     };  Runnable r2=new Runnable(){   public void run() {   System.out.println('helloWorld!');   }     };  Runnable r3=new Runnable(){   public void run() {   System.out.println('helloKitty!');   }     };  es.submit(r1);  es.submit(r2);  es.submit(r3); }}

6

频繁的从系统开辟新的线程会比较消耗系统资源,对程序的性能造成影响,我们可以设计出一个  线程池,线程run完之后滨骨灰死亡,而是会回到线程池中,    //使用jdk5提供的类创建线程池对象  ExecutorService es=Executors.newFixedThreadPool(个数);  向该线程冲中添加线程工作的内容    submit(Runnable run)    public void run(){   该方法用来写线程要做的事情   该方法没有返回值    }

推荐信息