Thread sample code

1. create a tread pool manager provide a thread pool.

package com.tian.jack.test;

import java.util.Vector;

public class ThreadPoolManager {
   
    @SuppressWarnings("unused")
    private int maxThread;
    @SuppressWarnings("unchecked")
    public Vector vector;

    public void setMaxThread(int threadCount) {
        maxThread = threadCount;
    }
   
    public ThreadPoolManager() {}

    @SuppressWarnings("unchecked")
    public ThreadPoolManager(int threadCount) {
        setMaxThread(threadCount);
        System.out.println("Starting thread pool...");
        vector = new Vector();
        for (int i = 1; i <= 10; i++) {
            SimpleThread thread = new SimpleThread(i);
            vector.addElement(thread);
            thread.start();
        }
    }

    public void process(String argument) {
        int i;
        for (i = 0; i < vector.size(); i++) {
            SimpleThread currentThread = (SimpleThread) vector.elementAt(i);
            if (!currentThread.isRunning()) {
                System.out.println("Thread " + (i + 1) + " is processing:"
                        + argument);
                currentThread.setArgument(argument);
                currentThread.setRunning(true);
                return;
            }
        }
        if (i == vector.size()) {
            System.out.println("pool is full, try in another time.");
        }
    }
}

 

Test this pool:

package com.tian.jack.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestThreadPool {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    System.in));
            String input;
            ThreadPoolManager manager = new ThreadPoolManager(10);
            while ((input = br.readLine()) != null) {
                manager.process(input);
            }
        } catch (IOException e) {
        }
    }
}

 

run this test, and input some string, the pool will provide thread from thread pool for you.

 

2. a retry queue test sample

 

package com.tian.jack.test;

public class _Doing {

    /**
     * @param args
     */
    private boolean isSuccess = false;

    public void _execute() throws Exception {
        isSuccess = false;
        _doSomething(isSuccess);
    }

    public void _doSomething(boolean isSuccess) throws Exception {
        if (isSuccess) {
            System.out.println("Done...");
        } else {
            throw new Exception("do something failure...");
        }
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean isSuccess) {
        this.isSuccess = isSuccess;
    }

}

----------------------------------------------------------------------
package com.tian.jack.test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class _RetryQueue extends Thread{
   
    private static final Logger logger = LoggerFactory.getLogger(_RetryQueue.class);
   
    private boolean terminal = false;
    //5s
    private int retryInterval = 5000;
   
    private int retries = 3;
   
    private static final Map<String, Integer> queue = new ConcurrentHashMap<String, Integer>();
   
    @Override
    public void run() {
        while(!terminal){
           
            System.out.println("");
            logger.debug("Thread START...");
            if(queue.size() <= 0){
                logger.debug("Thread STOP...");
                throw new RuntimeException("retry time is over, Thread STOPPED!");
            }
           
            try{
                Thread.sleep(retryInterval);
            }catch(InterruptedException e){   
            }
           
            for(String str : queue.keySet()){
                int numberRetries = queue.get(str);
                if(numberRetries < retries){
                   
                    try{
                        logger.debug("retry times {} ", numberRetries);
                        _Doing _doing = new _Doing();
                        _doing._execute();
                        queue.remove(str);
                        logger.debug("retry successfully....!!!");
                    }catch(Exception e){
                        queue.put(str, numberRetries+1);
                    }
                   
                }else{
                    logger.debug("retry times is over...force STOP it!!!!/n");
                    queue.remove(str);
                }
            }
        }
    }

    public static Map<String, Integer> getQueue() {
        return queue;
    }

}

-------------------------------------------------

package com.tian.jack.test;

public class _Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        _Doing _doing = new _Doing();
        try{
            _doing._execute();
        }catch(Exception e){
            _RetryQueue rq = new _RetryQueue();
            _RetryQueue.getQueue().put("sender1", 1);
            rq.start();
        }
       
    }

}

 

end...

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编程实例 MICROSOFT SOFTWARE LICENSE TERMS Microsoft Visual Studio 2005 and .NET Framework 2.0 Samples These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. The terms also apply to any Microsoft * updates, * supplements, * Internet-based services, and * support services for this software, unless other terms accompany those items. If so, those terms apply. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. If you comply with these license terms, you have the rights below. 1. INSTALLATION AND USE RIGHTS. You may install and use any number of copies of the software on your devices. 2. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS. a. Distributable Code. The software contains code that you are permitted to distribute in programs you develop if you comply with the terms below. i. Right to Use and Distribute. The code and text files listed below are 揇istributable Code.? * Sample Code. You may modify, copy, and distribute the source and object code form of the sample source code included in the subfolders of the project files. * Third Party Distribution. You may permit distributors of your programs to copy and distribute the Distributable Code as part of those programs. ii. Distribution Requirements. For any Distributable Code you distribute, you must * add significant primary functionality to it in your programs; * require distributors and external end users to agree to terms that protect it at least as much as this agreement; * display your valid copyright notice on your programs; and * indemnify, defend, and hold harmless Microsoft from any claims, including attorneys?fees, related to the distribution or use of your programs. iii. Distribution Restrictions. You may not * alter any copyright, trademark or patent notice in the Distributable Code; * use Microsoft抯 trademarks in your programs?names or in a way that suggests your programs come from or are endorsed by Microsoft; * distribute Distributable Code to run on a platform other than the Windows platform; * include Distributable Code in malicious, deceptive or unlawful programs; or * modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An Excluded License is one that requires, as a condition of use, modification or distribution, that * the code be disclosed or distributed in source code form; or * others have the right to modify it. 3. SCOPE OF LICENSE. The software is licensed, not sold. This agreement only gives you some rights to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not * work around any technical limitations in the software; * reverse engineer, decompile or disassemble the software, except and only to the extent that applicable law expressly permits, despite this limitation; * make more copies of the software than specified in this agreement or allowed by applicable law, despite this limitation; * publish the software for others to copy; * rent, lease or lend the software; * transfer the software or this agreement to any third party; or * use the software for commercial software hosting services. 4. BACKUP COPY. You may make one backup copy of the software. You may use it only to reinstall the software. 5. DOCUMENTATION. Any person that has valid access to your computer or internal network may copy and use the documentation for your internal, reference purposes. 6. EXPORT RESTRICTIONS. The software is subject to United States export laws and regulations. You must comply with all domestic and international export laws and regulations that apply to the software. These laws include restrictions on destinations, end users and end use. For additional information, see www.microsoft.com/exporting. 7. SUPPORT SERVICES. Because this software is 揳s is,?we may not provide support services for it. 8. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services. 9. APPLICABLE LAW. a. United States. If you acquired the software in the United States, Washington state law governs the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort. b. Outside the United States. If you acquired the software in any other country, the laws of that country apply. 10. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the software. This agreement does not change your rights under the laws of your country if the laws of your country do not permit it to do so. 11. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED 揂S-IS.? YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 12. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES. This limitation applies to * anything related to the software, services, content (including code) on third party Internet sites, or third party programs; and * claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law. It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages. Please note: As this software is distributed in Quebec, Canada, some of the clauses in this agreement are provided below in French. Remarque : Ce logiciel 閠ant distribu?au Qu閎ec, Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en fran鏰is. EXON蒖ATION DE GARANTIE. Le logiciel vis?par une licence est offert ?tel quel ? Toute utilisation de ce logiciel est ?votre seule risque et p閞il. Microsoft n抋ccorde aucune autre garantie expresse. Vous pouvez b閚閒icier de droits additionnels en vertu du droit local sur la protection dues consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualit?marchande, d抋d閝uation ?un usage particulier et d抋bsence de contrefa鏾n sont exclues. LIMITATION DES DOMMAGES-INT蒖蔜S ET EXCLUSION DE RESPONSABILIT?POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement ?hauteur de 5,00 $ US. Vous ne pouvez pr閠endre ?aucune indemnisation pour les autres dommages, y compris les dommages sp閏iaux, indirects ou accessoires et pertes de b閚閒ices. Cette limitation concerne : * tout ce qui est reli?au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers ; et * les r閏lamations au titre de violation de contrat ou de garantie, ou au titre de responsabilit?stricte, de n間ligence ou d抲ne autre faute dans la limite autoris閑 par la loi en vigueur. Elle s抋pplique 間alement, m阭e si Microsoft connaissait ou devrait conna顃re l掗ventualit?d抲n tel dommage. Si votre pays n抋utorise pas l抏xclusion ou la limitation de responsabilit?pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l抏xclusion ci-dessus ne s抋ppliquera pas ?votre 間ard. EFFET JURIDIQUE. Le pr閟ent contrat d閏rit certains droits juridiques. Vous pourriez avoir d抋utres droits pr関us par les lois de votre pays. Le pr閟ent contrat ne modifie pas les droits que vous conf鑢ent les lois de votre pays si celles ci ne le permettent pas.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值