在Java中编写程序:创建一个线程以模拟进程的就绪状态,执行状态和阻塞状态之间的转换。
答案:1 悬赏:20 手机版
解决时间 2021-02-13 17:33
- 提问者网友:浮克旳回音
- 2021-02-13 14:19
在Java中编写程序:创建一个线程以模拟进程的就绪状态,执行状态和阻塞状态之间的转换。
最佳答案
- 五星知识达人网友:末日狂欢
- 2021-02-13 14:50
boolean running = true;
static final Object LOCK = new Object();
int x = 0;
Runnable r1 = new Runnable() { //Task run in Main Thread
public void run() {
while(running) {
syncronized(LOCK) {
System.out.println("Main task starts running now");
while(running) {
System.out.println("Main task is to do some work with x);
x ++;
System.out.println("Main task makes x self added");
System.out.println("After work has done , Main task is going to be blocked soon");
LOCK.wait();
System.out.println("Main task is notifed and it resumes to run");
}
System.out.println("Main thread is going to end after FLAG running turned false");
}
}
Runnable r2 = new Runnable() { //The task cooperate with Main task
public void run() {
syncronized(LOCK) {
while(true) {
if(x < 100) {
running = true;
LOCK.notifyAll();
} else {
running = false;
LOCK.notifyAll();
break;
}
Thread.sleep(300);
}
}
}
}
public void main() {
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
// After this(t1.start()) called , t1 thread is ready until it starts running, but it's a very short // time for us.
t2.start();
}
随手写了些,3种状态应该很清楚了。 这个地方打代码格式对不齐,这个也没办法了。
static final Object LOCK = new Object();
int x = 0;
Runnable r1 = new Runnable() { //Task run in Main Thread
public void run() {
while(running) {
syncronized(LOCK) {
System.out.println("Main task starts running now");
while(running) {
System.out.println("Main task is to do some work with x);
x ++;
System.out.println("Main task makes x self added");
System.out.println("After work has done , Main task is going to be blocked soon");
LOCK.wait();
System.out.println("Main task is notifed and it resumes to run");
}
System.out.println("Main thread is going to end after FLAG running turned false");
}
}
Runnable r2 = new Runnable() { //The task cooperate with Main task
public void run() {
syncronized(LOCK) {
while(true) {
if(x < 100) {
running = true;
LOCK.notifyAll();
} else {
running = false;
LOCK.notifyAll();
break;
}
Thread.sleep(300);
}
}
}
}
public void main() {
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
// After this(t1.start()) called , t1 thread is ready until it starts running, but it's a very short // time for us.
t2.start();
}
随手写了些,3种状态应该很清楚了。 这个地方打代码格式对不齐,这个也没办法了。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯