50,535
社区成员
发帖
与我相关
我的任务
分享
class Run {
public static void main(String[] args) {
new Thread(new A()).start();
new Thread(new B()).start();
}
}
class A implements Runnable {
public static volatile boolean isStop = false; // 标记B是否完成运行
public void run() {
while(! isStop) { //B结束后A跳出循环
do sth;
}
System.out.println("B has stopped.")
}
}
class B implements Runnable {
public void run() {
do sth;
A.isStop = true; // 准备退出,将A中的标志变量改为true
}
}
class Run {
public static volatile boolean isStop = false; // 标记B是否完成运行
public static void main(String[] args) {
new Thread(new A()).start();
new Thread(new B()).start();
}
}
class A implements Runnable {
public void run() {
while(! Run.isStop) { //B结束后A跳出循环
do sth;
}
System.out.println("B has stopped.")
}
}
class B implements Runnable {
public void run() {
do sth;
Run.isStop = true; // 准备退出,将Run中的标志变量改为true
}
}
package v_2.socket;
public class Run {
public static void main(String args[]) {
Object lock=new Object();
Thread a=new Thread(new A(lock));
Thread b=new Thread(new B(lock));
a.setName("a");
b.setName("b");
a.start();
b.start();
}
}
class A implements Runnable {
//public static volatile boolean isStop = false; // 标记B是否完成运行
Object lock;
public A(Object o){
this.lock=o;
}
public void run() {
/* while(! isStop) { //B结束后A跳出循环
do sth;
}
System.out.println("B has stopped.")*/
synchronized(lock){
if(Thread.currentThread().getName().equals("a")){
try {
lock.wait();//a等等,让b来通知它来运行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B has stopped.");
}
}
}
class B implements Runnable {
/* public void run() {
do sth;
A.isStop = true; // 准备退出,将A中的标志变量改为true
}*/
Object lock;
public B(Object o){
this.lock=o;
}
@Override
public void run() {
synchronized(lock){
System.out.println("我是B线程 ,我现在运行!");
System.out.println("我现在运行完啦,叫A运行...");
lock.notifyAll();//lock.notifyAll();假如是多条线程
}
}
}
我是B线程 ,我现在运行!
我现在运行完啦,叫A运行...
B has stopped.