线程 实例

上一篇 / 下一篇  2007-05-30 17:33:51 / 个人分类:备忘录

  • 文件版本: V1.0
  • 开发商: 本站原创
  • 文件来源: 本地
  • 界面语言: 简体中文
  • 授权方式: 免费
  • 运行平台: Win9X/Win2000/WinXP

// ThreadDemo.java
public class ThreadDemo
{
 public static void main (String [] args)
 {
  MyThread2 mt = new MyThread2 ();
  mt.start ();
  for (int i = 0; i < 50; i++)
   System.out.println ("i = " + i + ", i * i = " + i * i);
  
 }
}

class MyThread2 extends Thread
{
 public void run ()
 {
  for (int count = 1, row = 1; row < 20; row++, count++)
  {
   for (int i = 0; i < count; i++)
    System.out.print ('*');
   System.out.print ('\n');
  }
 }
}

public class SimpleThread extends Thread {
  private int countDown = 500;
  private int threadNumber;
  private static int threadCount = 0;
  public SimpleThread() {
    threadNumber = ++threadCount;
    System.out.println("Making " + threadNumber);
  }
  public void run() {
    while(true) {
      System.out.println("Thread " +
        threadNumber + "(" + countDown + ")");
      if(--countDown == 0) return;
    }
  }
 
 
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++)
      new SimpleThread().start();
    System.out.println("All Threads Started");
  }
}

public class MyTestThread  implements Runnable {
private boolean _done = false;
public synchronized boolean getDone()
{
return _done;
}
public synchronized void setDone(boolean b)
{
_done = b;
}

public void run( ) {
boolean done;
done = getDone();
while (!done) {
System.out.println("not finished");
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
return;
}
}
}
}

public class TestThreads {
 public static void main(String args[]) {

  MyThread a = new MyThread("Thread A");
  MyThread b = new MyThread("Thread B");
  MyThread c = new MyThread("Thread C");
  a.start();
  b.start();
  c.start();
 }
}

class MyThread extends Thread {
 String n;

 MyThread(String name) {
  n = name;
 }

 public void run() { 
  int iterations = (int)(Math.random()*100); //random()返回 0.0 到 1.0 间的伪随机数 
  int sleepinterval = (int)(Math.random()*1000); 
    System.out.println(n + " running for " + iterations +" iterations");  
    System.out.println(n + " sleeping for " + sleepinterval + "ms between loops");
    for (int i = 0;i<iterations; i++) {  
     System.out.println(n +" " + i); 
     try {   
      Thread.sleep(sleepinterval);
     } catch (InterruptedException e) {}       
    } 
 }}

import java.util.*;

public class Hi {
public static void main(String args[])throws java.io.IOException {
 TimerTask task = new TimerTask() {
  public void run() {
   System.out.println("Hi");
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 500);
System.out.println("Press ENTER to stop");
System.in.read(new byte[10]);
timer.cancel();
}}

/**
 * CalculatePrimes -- calculate as many primes as we can in ten seconds
 */

public class CalculatePrimes extends Thread {

    public static final int MAX_PRIMES = 1000000;
    public static final int TEN_SECONDS = 1000;

    public volatile boolean finished = false;

    public void run() {
        int[] primes = new int[MAX_PRIMES];
       
        int count = 0;

        for (int i=2; count<MAX_PRIMES; i++) {

            // Check to see if the timer has expired
            if (finished) {
                break;
            }

            boolean prime = true;
            for (int j=0; j<count; j++) {
                if (i % primes[j] == 0) {
                    prime = false;
                    break;
                }
            }

            if (prime) {
                primes[count++] = i;
                System.out.println("Found prime: " + i);
            }
        }
    }

    public static void main(String[] args) {
        CalculatePrimes calculator = new CalculatePrimes();
        calculator.start();
      
        try {
            Thread.sleep(TEN_SECONDS);
        }
        catch (InterruptedException e) {
            // fall through
        }

        calculator.finished = true;
    }
}

import java.io.*;

class Daemon extends Thread {
  private static final int SIZE = 10;
  private Thread[] t = new Thread[SIZE];
  public Daemon() {
    setDaemon(true);
    start();
  }
  public void run() {
    for(int i = 0; i < SIZE; i++)
      t[i] = new DaemonSpawn(i);
    for(int i = 0; i < SIZE; i++)
      System.out.println(
        "t[" + i + "].isDaemon() = "
        + t[i].isDaemon());
    while(true)
      yield();
  }
}

class DaemonSpawn extends Thread {
  public DaemonSpawn(int i) {
    System.out.println(
      "DaemonSpawn " + i + " started");
    start();
  }
  public void run() {
    while(true)
      yield();
  }
}

public class Daemons {
  public static void main(String[] args) {
    Thread d = new Daemon();
    System.out.println(
      "d.isDaemon() = " + d.isDaemon());
    // Allow the daemon threads to finish
    // their startup processes:
    BufferedReader stdin =
      new BufferedReader(
        new InputStreamReader(System.in));
    System.out.println("Waiting for CR");
    try {
      stdin.readLine();
    } catch(IOException e) {}
  }
}

import java.util.*;   

  
public class TimerTaskDemo extends TimerTask {   
       
    String index;   
  
    Timer myTimer = new Timer();   
  
    public TimerTaskDemo(String index) {   
        this.index = index;   
    }   
  
    public void run() {   
        System.out.println(index);   
    }   
  
    /**  
     * @param args  
     */  
    public static void main(String[] args) {   
        TimerTaskDemo myTask1 = new TimerTaskDemo("First task");   
        myTask1.start(0,3);   
        TimerTaskDemo myTask2 = new TimerTaskDemo("Second task");   
        myTask2.start(0,1);   
  
        try{   
            Thread.sleep(6000);   
        }   
        catch(InterruptedException e){               
        }      
           
        myTask1.end();   
        myTask2.end();//程序结束时用cancel()结束Timer   
  
    }   
    public void start(int delay, int internal) {   
        myTimer.schedule(this, delay * 1000, internal * 1000); //利用timer.schedule方法   
    }   
    public void end(){   
        myTimer.cancel();   
    }   

相关阅读:

TAG: 备忘录

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-24  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 5840
  • 日志数: 4
  • 文件数: 8
  • 建立时间: 2007-04-25
  • 更新时间: 2007-06-17

RSS订阅

Open Toolbar