代码:
//java 一个线程唤醒另一个线程,这里是主线程唤醒T1线程
import java.util.Scanner;
public class Main {
static String s;
public static void main(String[] args) {
while(true) {
T1 t1 = new T1();
t1.start();
Scanner sc=new Scanner(System.in);
s=sc.nextLine(); //键盘数据存于静态全局变量中
synchronized (t1){ //synchronized()必须在同一个线程
t1.notify(); //唤醒T1线程
}
}
}
}
class T1 extends Thread{
public synchronized void run() {
while (true) {
try {
wait(); //没有唤醒之前,一值等待
System.out.println(Main.s);
Main.s =null;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
改进代码,更具实用性,一个线程唤醒另一个线程
//java 主线程唤醒另一个线程,这里是主线程唤醒T1线程
import java.util.Scanner;
public class Main {
static String s;
public static void main(String[] args) {
T2 t2=new T2();
t2.start();
}
}
class T2 extends Thread{
public void run() {
while (true) {
T1 t1 = new T1(); //
t1.start(); //这两句代码必须放在scanner 之前,因为scanner 有阻塞,如放在后面,则运行不到
Scanner sc = new Scanner(System.in);
Main.s = sc.nextLine(); //键盘数据存于静态全局变量中
synchronized (t1) { //synchronized()必须在同一个线程
t1.notify(); //唤醒T1线程
}
}
}
}
class T1 extends Thread{
public synchronized void run() {
while (true) {
try {
wait(); //没有唤醒之前,一值等待
System.out.println(Main.s);
Main.s =null;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
突然联想到:这种思路是不是就是NIO的事件触发?如T2是ServerScket,它收到socket就去唤醒T1来读取数据.
下面是写的服务器代码,T2负责接收Socket,如没有socket,则T1等待,甚至T1还可以再分一个线程T3, T1notify() T3流read()的wait().
//java 主线程唤醒另一个线程,这里是主线程唤醒T1线程
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
static Socket s;
public static void main(String[] args) {
T2 t2=new T2();
t2.start();
}
}
class T2 extends Thread{
public void run() {
try {
ServerSocket ss=new ServerSocket(5000);
while (true) {
T1 t1 = new T1(); //
t1.start(); //这两句代码必须放在scanner 之前,因为scanner 有阻塞,如放在后面,则运行不到
Main.s=ss.accept();
synchronized (t1) { //synchronized()必须在同一个线程
t1.notify(); //唤醒T1线程
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
class T1 extends Thread{
public synchronized void run() {
while (true) {
try {
wait(); //没有唤醒之前,一值等待
InputStream is=Main.s.getInputStream();
System.out.println((char)is.read());
sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}