线程守护 --小例子

 

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yanfazhongxin on 2020-04-22.
 * 守护线程
 */
public class 加密解密 {
    public static void main(String[] args) {
        //两条线程谁启动先没有影响
        Thread t2 = new Thread(new Log_thread());
        t2.setDaemon(true);//设定为 守护线程
        t2.start();
        Thread t1 = new Thread(new Decode());
        t1.start();

    }
}
class Decode implements Runnable {
    static List<String> list = new ArrayList<>();
    String password = String.valueOf(random(4));

    public char[] random(int index) {
        char[] re = new char[index];
        Math.random();
        for (int i = 0; i < index; i++) {
            // 指定随机范围 : 64-90
            re[i] = (char) ((Math.random() * 26 + 64));
        }
        return re;

    }


    @Override
    public void run() {
        System.out.println("本次随机密码是:" + password);
        boolean cnt = true;
        while (cnt) {
            String str = String.valueOf(random(4));
            if (str.equals(password)) {
                System.out.println("匹配密码正确是:" + password);
                list.add(str);
                cnt = false;
            } else
                // System.out.println(str+" 匹配失败");
                list.add(str);
        }

    }

}
class Log_thread implements Runnable {
    @Override
    public void run() {
        System.out.println(" Log_thread implements");
       // for (int i = 0; i < Decode.list.size(); i++) {
        while(true){

            if ((Decode.list == null)||(Decode.list.size()<1)) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else
                System.out.println( "  匹配的密码可能是:" + Decode.list.remove(0));
        }
    }
}
posted @ 2020-06-12 10:49  海蓝7  阅读(205)  评论(0编辑  收藏  举报