1.下面的程序定义了一个线程类,请填空把程序补充完整。 public class MyThread implements (1) { private int num = 0; private boolean stop = false; public static void main(String[] args
时间: 2024-04-26 20:23:54 浏览: 94
) {
MyThread thread = new MyThread();
thread.start();
}
public void run() {
while(!stop) {
num++;
System.out.println("Current number is: " + num);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public void stopRunning() {
stop = true;
}
}
Runnable
相关问题
.下面的程序定义了一个线程类,请填空把程序补充完整。 public class MyThread implements (1) { private int num = 0; private boolean stop = false; public static void main(String[] args) { MyThread my = new MyThread(); Thread td = new Thread(my);
public class MyThread implements Runnable {
private int num = 0;
private boolean stop = false;
public void run() {
while(!stop) {
System.out.println("num = " + num);
num++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread my = new MyThread();
Thread td = new Thread(my);
td.start();
}
}
分析以下代码,要实现多个线程一起完成打印1-3数据的功能,完成横线处缺失部分的代码() class MyThread implements Runnable { private int num = 3; @Override public void run() { while (true) _____________请选择正确的选项__________ { if (num == 0) break; else { System.out.println(Thread.currentThread().getName() + " - " + num); num--; } } } } MyThread my=new MyThread(); Thread t1=new Thread(my) Thread t2=new Thread(my) T1.start() my.run() T2.start() my.run() class MyThread extends Thread{} MyThread th1=new MyThread(); MyThread th2=new MyThread(); th1.start() th1.run() th2.start() th2.run() synchronized (MyThread.class) synchronized (this) synchronized () lock.lock();
正确的选项应该是 synchronized (this)。因为多个线程要共享同一个 Runnable 对象 my,所以需要使用同步锁来保证线程安全。synchronized (this) 表示使用当前对象 my 作为锁,只有获得锁的线程才能执行其中的代码,其他线程需要等待。而 synchronized (MyThread.class) 则是使用 MyThread 类作为锁,这样会限制所有 MyThread 的对象同时只能执行一个代码块,与本题的需求不符。synchronized() 是无法通过编译的,lock.lock() 则需要在代码中显式地释放锁,容易出现死锁等问题,不太适合此处的场景。
阅读全文