用兩個執行緒玩猜數字遊戲
阿新 • • 發佈:2019-01-05
package duoxiancheng; import java.util.Random; class guessThread implements Runnable{ int num; public synchronized void run() { // TODO Auto-generated method stub Random r = new Random(); num= r.nextInt(100); } public int getNum() { return num; } public void setNum(int num) { this.num = num; } }
package duoxiancheng; import java.util.Random; public class example2{ public static void main(String[] args) { // TODO Auto-generated method stub guessThread fth=new guessThread(); Thread first=new Thread(fth);//正確數字執行緒 first.run(); while(true) { try { Thread.sleep(10); guessThread sth=new guessThread(); Thread second=new Thread(sth); // Thread second=new Thread(new guessThread()); second.interrupt(); //喚醒這個程序 second.run(); Thread.sleep(10); first.interrupt(); System.out.println("隨機生成的數為"+fth.getNum()+",猜的數字為:"+sth.getNum()); if(sth.getNum()>fth.getNum()) System.out.println("猜大了"); else if(sth.getNum()<fth.getNum()) System.out.println("猜小了"); else {System.out.println("猜對了"); break;} } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }