用Java并行/多线程创建现有代码 [英] Make an existing code in Java parallel/multithread

查看:303
本文介绍了用Java并行/多线程创建现有代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的抓取工具。我想让我当前的代码在几个线程中运行。你能给我一些教程或文章来帮助我完成这个测试吗?

I have a very simple crawler. I want to make my current code run in a few threads. Could you provide me a little tutorial or article to help me achive this test?

我原来是.Net开发人员和.Net我运行代码没什么问题在多线程中但不幸的是我对Java中的线程一无所知。

I'm originally a .Net developer and in .Net I have no problem whatsoever running codes in multithread but unfortunately I don't know anything about threads in Java.

我的爬虫是一个命令行软件所以不用担心GUI。

My crawler is a command-line software so don't worry about GUI.

提前谢谢。

推荐答案

Java通过Thread类进行多线程处理。使现有代码多线程的最常见方法之一是使用Runnable接口来定义在线程启动时要调用的内容,然后将其启动。

Java does multithreading through the Thread class. One of the most common ways to make existing code multithreaded is to use the Runnable interface to define what you want to call at thread start, and then start it off.

public class SomeFunctions
{
  public static void FunctionA() {}
  public static void FunctionB() {}
  public static void FunctionC() {}
}

// ...
Thread t1 = new Thread(new Runnable() {
   public void run() {
      SomeFunctions.FunctionA();
   }
});
t1.start();

// (rinse and repeat for the other functions)

干编码,但它应该至少得到一般概念。当然,只要你进入多线程领域,你就会遇到并发问题,并且需要确保所有内容都经过适当的同步,等等,但任何语言都会遇到这些问题。

Dry coded, but it should at least get the general concept across. Of course, as soon as you go into multithreading land, you have concurrency issues and need to make sure everything is appropriately syhchronized, etc., but any language will have those issues.

如果您担心同步,可以使用一些工具。最简单的是Java内置的递归互斥锁功能,即synchronized关键字。 java.util.concurrent和java.util.concurrent.locks包中的各种类也可以使用更经典的方法,例如Semaphore和ReadWriteLock

If you're worried about synchronization, you have a few tools at your disposal. The easiest is the recursive mutex functionality built into Java, the "synchronized" keyword. More classical means are also available through various classes in the java.util.concurrent and java.util.concurrent.locks packages such as Semaphore and ReadWriteLock

http://download.oracle.com/javase/6/docs/api/java /util/concurrent/package-summary.html
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html

这篇关于用Java并行/多线程创建现有代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆