您的位置:首页 >> 编程开发 >> Java >> J2SE >> 正文
J2SE RSS
 

Java之多线程(1)

http://www.rdxx.com 05年07月24日 21:14 JR 我要投稿

关键词: 多线程 , Java , 线程

    }
}
class ThreadTest implements Runnable
{
    public void run()
    {
        String str=new String();
        int i=0;
        while(true)
        {
            System.out.println(Thread.currentThread().getName()+" "+i++);
        }
    }
}

EX:
/*
编写一个类MyThread,它继承自Thread类,该类有两个变量:线程的名字整型变量delay,该类的构造函数有两个参数,
分别初始化str和delay,用String类的对象str表示,类的frun方法中,先让线程休眠delay毫秒后,再打印线程的名字。
编写应用程序,创建MyThread类的三个对象t1、t2和t3,分别指定线程名字为“线程A”、“线程B”和“线程C”,
休眠时间为1000ms、2000ms、3000ms,并启动这三个线程。
*/
public class Exercise14 {
  public static void main(String args[])
  {
    MyThread t1,t2,t3 ;
    t1 = new MyThread("线程A",1000);
    t2 = new MyThread("线程B",2000);
    t3 = new MyThread("线程C",3000);
    t1.start();
    t2.start();
    t3.start();
  }
}
class MyThread extends Thread
{
  private String str ;
  private int delay ;
  public MyThread(String s,int d)
  {
    super(s) ;
    delay = d ;
  }
  public void run()
  {
    try {
      Thread.sleep(delay);
    }
    catch (InterruptedException ex) {
      ex.printStackTrace();
    }
    System.out.println(getName()+"运行!");
  }


}练习2:
/*
编写一个类A,并实现Runnable接口,该类有两个变量:str(String类型)和delay(int类型),该类的构造方法有两个参数,
分别初始化str和delay。类中的run方法如下实现,休眠delay毫秒后,打印str。编写应用程序,分别用类A的两个对象作为参数
创建两个线程对象t1、t2;类A的两个对象的str分别指定为“A类对象1”、“A类对象2”,休眠时间为1000ms、2000ms
*/
public class Exercise15 {
  public static void main(String args[])
  {
    Thread t1,t2 ;
    t1 = new Thread(new A("A类对象1",1000)) ;
    t2 = new Thread(new A("A类对象2",2000)) ;
    t1.start();
    t2.start();
    try {
      t1.join();

共21页  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21


 
 
标签: 多线程 , Java , 线程 打印本文
 
 
  相关资讯
RSS
 
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站