例题1
package com.lsq.study.锁;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
PrintInteger_ printInteger = new PrintInteger_();
new Thread(printInteger).start();
InputApl inputApl = new InputApl(printInteger);
inputApl.start();
}
}
class PrintInteger_ implements Runnable{
private boolean flag=true;
public void setFlag(boolean flag) {
this.flag = flag;
}
public void printRandom(){
while (flag) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (this) {
System.out.println(Thread.currentThread().getName()+"当前整数为:" + (int) (Math.random() * 100 + 1));
}
}
}
@Override
public void run() {
printRandom();
}
}
class InputApl extends Thread{
private PrintInteger_ printInteger;
private Scanner scanner=new Scanner(System.in);
public InputApl(PrintInteger_ printInteger) {
this.printInteger = printInteger;
}
@Override
public void run() {
while(true){
System.out.println("请输入你的指令(Q)表示退出:"+Thread.currentThread().getName());
char c = scanner.next().toUpperCase().charAt(0);
if (c=='Q'){
printInteger.setFlag(false);
break;
}
}
}
}
使用键盘监听的方式(只用了一个线程)
package com.lsq.study.锁;
import javafx.scene.input.KeyCode;
import jdk.nashorn.internal.runtime.regexp.JoniRegExp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.security.Key;
public class Demo02 extends JFrame{
KeyPress keyPress=null;
static PrintInteger printInteger=null;
public static void main(String[] args) {
printInteger=new PrintInteger();
new Thread(printInteger).start();
Demo02 demo02 = new Demo02();
}
public Demo02(){
keyPress=new KeyPress(printInteger);
this.add(keyPress);
this.addKeyListener(keyPress);
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
class PrintInteger implements Runnable{
private boolean flag=true;
public void setFlag(boolean flag) {
this.flag = flag;
}
public void printRandom(){
while (flag) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (this) {
System.out.println(Thread.currentThread().getName()+"当前整数为:" + (int) (Math.random() * 100 + 1));
}
}
}
@Override
public void run() {
printRandom();
}
}
class KeyPress extends JPanel implements KeyListener{
PrintInteger printInteger;
public KeyPress(PrintInteger printInteger) {
this.printInteger = printInteger;
}