多线程Thread

来源:互联网 发布:jsp网上商城系统 源码 编辑:程序博客网 时间:2024/05/29 05:54

一、主测试函数

public static void main(String[] args) {
  for (int i = 0; i < 2; i++) {

   Thread thread = new Thread(new CyOperation(1,i)); // ---- I
   thread.start();
  }
   System.out.println(" 第一次!");  //  -----II
  for (int i = 0; i < 2; i++) {
   Thread thread = new Thread(new CyOperation(2,i));  //  ----- III
   thread.setPriority(10);
   thread.start(); // 告诉jvm,该线程已经准备好,何时执行由jvm决定。 此处达到了多线程的要求 。III处代码会和VI处代码同时执行,VI是主线程,III 会相对的异步执行!

   thread.run();  // 对象中继承Runnable必须实现的一个方法,线程中使用该方法 和调用普通方法一样,失去线程的明显特征。VI会等到III 处执行完后再执行,(主线程停滞,暂时这么理解)
  
  }
  System.out.println(" 第二次! ");  // ---- VI
 }

 

二、CyOperation 类文件内容


public class CyOperation implements java.lang.Runnable {
 public CyOperation(int i, int j) {
  this.n = i;
  this.m = j;
 }

 private int n = 0;
 private int m = 0;

 public void run() {
  for (int i = 0; i < 3; i++) {
   // try {
   // Thread.sleep(1000);
   // } catch (InterruptedException e) {
   // // TODO Auto-generated catch block
   // e.printStackTrace();
   // }
   this.getHello(i);
  }
 }

 public synchronized String getHello(int i) {

  Service serviceModel = new ObjectServiceFactory()
    .create(Operation.class);
  XFire xfire = XFireFactory.newInstance().getXFire();
  XFireProxyFactory factory = new XFireProxyFactory(xfire);

  String serviceUrl = "http://192.168.0.112:88/CyWsServer/services/OperaByCy";

  Operation client = null;
  try {
   client = (Operation) factory.create(serviceModel, serviceUrl);
  } catch (MalformedURLException e) {
  }

  String result = "";
  try {
   Thread thread = new Thread();
   thread.start();

   result = client.JiaNumber(i * 0.25, i * 10);
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println(n+" = "+m+" 第 " + i + " 次" + result);

  return result;
 }

 

 

原创粉丝点击