Topic 1: write an application using Java multi-threading mechanism to achieve synchronization output time display.
/ * Use the Runnable interface class to create a thread object, override the run () method ** /
Code
public class timetext { public static void main(String[] args) { Thread thread =new Thread(new time()); thread.start(); } }
import java.util.Date; public class time implements Runnable { public void run() { Date date =null; while(true){ date=new Date(); System.out.println(date); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
operation result
Write an application using Java multi-threading mechanism to achieve guessing game (an integer between 0 to 100 range of random numbers).
Code
public class Test { public static void main(String[] args) { game ga=new game(); ga.rand.start(); ga.input.start(); } }
import java.util.*; public class game implements Runnable { Thread rand,input; int inputnum,random,flag; boolean a=false,b=false; public game(){ rand=new Thread(this); input=new Thread(this); } public void run() { while(true){ compare(); if(flag==3) return; } } public synchronized void compare(){ if(Thread.currentThread()==rand&&b==false){ random=(int)(Math.random()*100)+1; System.out.println("猜数游戏开始!"); a=true; b=true; } IF (Thread.currentThread () == RAND) { IF (A == to true) { the try { the wait (); } the catch (InterruptedException E) { e.printStackTrace (); } } IF (InputNum <Random) { the System .out.println ( "! Please try to guess the small guess!"); In Flag =. 1; } the else IF (InputNum> Random) { System.out.println ( "! Please try to guess guess big!"); In Flag = 2; } the else IF (Random InputNum ==) { System.out.println ( "Congratulations, you guessed it!"); In Flag =. 3; } a = to true; notifyAll (); } if(Thread.currentThread()==input){ while(a==false){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if(flag<3){ System.out.println("请输入您猜的数!"); Scanner r=new Scanner(System.in); inputnum=r.nextInt(); } a=false; } notifyAll(); } }
operation result