Javaの一般的なスレッド方法
実施例1:現在のスレッドは中断され
Thread.sleep(1000);現在のスレッドが中断されていることを示す1000ミリ秒、他のスレッド影響を受けていない
(1000)のThread.sleepは、現在のスレッドのスリープ時間ので、おそらくそこに停止するようにしている、例外割り込み例外:InterruptedExceptionをスローし、それがスローされますInterruptedExceptionあるアウト
package multiplethread;
public class TestThread {
public static void main(String[] args) {
Thread t1= new Thread(){
public void run(){
int seconds =0;
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf("已经玩了LOL %d 秒%n", seconds++);
}
}
};
t1.start();
}
}
例2:現在のスレッドを追加します。
まず説明し、メインスレッドの概念に
すべてのプロセスを、mainメソッドが実行を開始され、メインスレッド、ある少なくとも一つのスレッドがあるだろう、があるだろう見えないメインスレッドが存在します。
42行t.joinで行う、すなわちことを示すメインスレッド内のスレッドの添加。
メインスレッドは、それがダウンして実行され、完了すると、スレッドの終了を待ちます。
package multiplethread;
import charactor.Hero;
public class TestThread {
public static void main(String[] args) {
final Hero gareen = new Hero();
gareen.name = "盖伦";
gareen.hp = 616;
gareen.damage = 50;
final Hero teemo = new Hero();
teemo.name = "提莫";
teemo.hp = 300;
teemo.damage = 30;
final Hero bh = new Hero();
bh.name = "赏金猎人";
bh.hp = 500;
bh.damage = 65;
final Hero leesin = new Hero();
leesin.name = "盲僧";
leesin.hp = 455;
leesin.damage = 80;
Thread t1= new Thread(){
public void run(){
while(!teemo.isDead()){
gareen.attackHero(teemo);
}
}
};
t1.start();
//代码执行到这里,一直是main线程在运行
try {
//t1线程加入到main线程中来,只有t1线程运行结束,才会继续往下走
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread t2= new Thread(){
public void run(){
while(!leesin.isDead()){
bh.attackHero(leesin);
}
}
};
//会观察到盖伦把提莫杀掉后,才运行t2线程
t2.start();
}
}
例3:スレッドの優先順位
スレッドが競合している場合は、優先度の高いスレッドがCPUリソースを得るための大きなチャンスがあります
。この効果を実証するために、それは休止時間を除去する必要がある、複数のスレッドそれぞれがCPUリソースを占有しようとする
血液英雄の量を増加させると同時に、 100倍、攻撃はプレゼンテーションの優先順位を観察するのに十分な時間が持っている、1に減少し
、それはより多くのCPUリソースのコード実行に勝つので、スレッド1の優先順位は、MAX_PRIORITYある、として見ることができます
package charactor;
import java.io.Serializable;
public class Hero{
public String name;
public float hp;
public int damage;
public void attackHero(Hero h) {
//把暂停时间去掉,多条线程各自会尽力去占有CPU资源
//线程的优先级效果才可以看得出来
// try {
//
// Thread.sleep(0);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
h.hp-=damage;
System.out.format("%s 正在攻击 %s, %s的血变成了 %.0f%n",name,h.name,h.name,h.hp);
if(h.isDead())
System.out.println(h.name +"死了!");
}
public boolean isDead() {
return 0>=hp?true:false;
}
}
package multiplethread;
import charactor.Hero;
public class TestThread {
public static void main(String[] args) {
final Hero gareen = new Hero();
gareen.name = "盖伦";
gareen.hp = 6160;
gareen.damage = 1;
final Hero teemo = new Hero();
teemo.name = "提莫";
teemo.hp = 3000;
teemo.damage = 1;
final Hero bh = new Hero();
bh.name = "赏金猎人";
bh.hp = 5000;
bh.damage = 1;
final Hero leesin = new Hero();
leesin.name = "盲僧";
leesin.hp = 4505;
leesin.damage = 1;
Thread t1= new Thread(){
public void run(){
while(!teemo.isDead()){
gareen.attackHero(teemo);
}
}
};
Thread t2= new Thread(){
public void run(){
while(!leesin.isDead()){
bh.attackHero(leesin);
}
}
};
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
例4:一時停止
他のスレッドがCPUリソースを消費するより多くの機会を持つことができるように一時的に停止し、現在のスレッド、
package multiplethread;
import charactor.Hero;
public class TestThread {
public static void main(String[] args) {
final Hero gareen = new Hero();
gareen.name = "盖伦";
gareen.hp = 61600;
gareen.damage = 1;
final Hero teemo = new Hero();
teemo.name = "提莫";
teemo.hp = 30000;
teemo.damage = 1;
final Hero bh = new Hero();
bh.name = "赏金猎人";
bh.hp = 50000;
bh.damage = 1;
final Hero leesin = new Hero();
leesin.name = "盲僧";
leesin.hp = 45050;
leesin.damage = 1;
Thread t1= new Thread(){
public void run(){
while(!teemo.isDead()){
gareen.attackHero(teemo);
}
}
};
Thread t2= new Thread(){
public void run(){
while(!leesin.isDead()){
//临时暂停,使得t1可以占用CPU资源
Thread.yield();
bh.attackHero(leesin);
}
}
};
t1.setPriority(5);
t2.setPriority(5);
t1.start();
t2.start();
}
}
例5:デーモンスレッド
スレッドデーモンコンセプトはこれです:プロセスは、すべてのスレッドが現在のプロセスを終了し、時間を守るのスレッドされている場合。
同社は、営業部門、生産部門とビジネスはこれらの部門にリンクされている場合。
また、これらの部門、物流管理、およびその他のサポートがあります。
会社の営業部門、生産部門が溶解している場合は、唯一の物流や行政、その後、会社は解散することができます。
プロセスが唯一のデーモンスレッドは、プロセスが自動的に終了するかどうデーモンスレッドは、そのサポートと同等です。
デーモンスレッドは、通常、ロギング、パフォーマンス統計のためなどに使用されます。
package multiplethread;
public class TestThread {
public static void main(String[] args) {
Thread t1= new Thread(){
public void run(){
int seconds = 0;
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf("已经玩了LOL %d 秒%n", seconds++);
}
}
};
t1.setDaemon(true);
t1.start();
}
}
練習:コードをクラック
ランダムな文字列の長さを生成すると、パスワードとしてこの文字列3であります
割れたスレッドを作成すると、使用ブルートフォース方法は、パスワードと一致します
マッチングを印刷するために使用される文字列のログスレッドを作成し、このスレッドがデーモンスレッドをログに記録するように設計されています
ヒント:スレッド生成されたパスワードブルートフォース法を破るためには、容器内に配置することができる、スレッドがコンテナからパスワードやプリントアウトを思い付くし続けることが記録されます。それが発見された場合、コンテナは空であり、そして空削除ノンストップ、および印刷しないことが判明した場合、1秒休みます。
答え:
徹底的なパスワードのスレッド
package multiplethread;
import java.util.List;
public class PasswordThread extends Thread{
private boolean found = false;
private String password;
private List<String> passwords;
public PasswordThread(String password, List<String> passwords) {
this.password = password;
this.passwords = passwords;
}
public void run(){
char[] guessPassword = new char[password.length()];
generatePassword(guessPassword, password);
}
public void generatePassword(char[] guessPassword, String password) {
generatePassword(guessPassword, 0, password);
}
public void generatePassword(char[] guessPassword, int index, String password) {
if (found)
return;
for (short i = '0'; i <= 'z'; i++) {
char c = (char) i;
if (!Character.isLetterOrDigit(c))
continue;
guessPassword[index] = c;
if (index != guessPassword.length - 1) {
generatePassword(guessPassword, index + 1, password);
} else {
String guess = new String(guessPassword);
//穷举每次生成的密码,都放进集合中
passwords.add(guess);
if (guess.equals(password)) {
System.out.println("找到了,密码是" + guess);
found = true;
return;
}
}
}
}
}
ロギングデーモンスレッド
package multiplethread;
import java.util.List;
public class LogThread extends Thread{
private boolean found = false;
private List<String> passwords;
public LogThread(List<String> passwords) {
this.passwords = passwords;
this.setDaemon(true);//把记日志的这个线程,设置为守护线程
}
public void run(){
while(true){
while(passwords.isEmpty()){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String password = passwords.remove(0);
System.out.println("穷举法本次生成的密码是:" +password);
}
}
}
テストカテゴリ
package multiplethread;
import java.util.ArrayList;
import java.util.List;
public class TestThread {
public static boolean found = false;
public static void main(String[] args) {
String password = randomString(3);
System.out.println("密码是:" + password);
List<String> passwords = new ArrayList<>();
new PasswordThread(password,passwords).start();
new LogThread(passwords).start();
}
private static String randomString(int length) {
String pool = "";
for (short i = '0'; i <= '9'; i++) {
pool += (char) i;
}
for (short i = 'a'; i <= 'z'; i++) {
pool += (char) i;
}
for (short i = 'A'; i <= 'Z'; i++) {
pool += (char) i;
}
char cs[] = new char[length];
for (int i = 0; i < cs.length; i++) {
int index = (int) (Math.random() * pool.length());
cs[i] = pool.charAt(index);
}
String result = new String(cs);
return result;
}
}