我们当前的课程作业指定我们应该使用“对象池管理器”设计模式为线程池创建一个管理器,该模式会生成一定数量的线程。这些线程的所有权将转移给客户端,并在客户端使用完毕后返回到池中。如果池中不存在线程,则客户端必须等待。
我的困惑来自于这样一个事实:线程被认为是不可重用的,这违背了池化它们的目的。我对作业的理解是否错误?
我们有2个主题:
他们没有任务安排
他们也没有同步机制
他们的任务是:
将值读入寄存器
递增寄存器中的值
将值写回位置X.
在开始时,X包含值0.两个线程在同一位置修改值.
两个线程同时启动并执行1000次迭代.
问题:两个线程完成后,X的最小值是多少?(不是1000而不是2000)
我已经同步了Integer对象a,我期待输出1 2 3 4 5 6 7 8 9但是它仍然给我其他输出.问题是因为我已经同步了每个线程试图访问的变量.
package thread;
public class BasicThread extends Thread {
static Integer a=new Integer(0);
void incr() {
synchronized (a) {
a++;
System.out.println(a);
}
}
public void run() {
incr();
incr();
incr();
}
public static void main(String[] args) throws InterruptedException {
BasicThread bt=new BasicThread();
BasicThread bt1=new BasicThread();
BasicThread bt2=new BasicThread();
bt.start();
bt1.start();
bt2.start();
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试用Java编写我的第一个多线程程序.我无法理解为什么我们需要围绕for循环进行此异常处理.当我在没有try/catch子句的情况下编译时,它会产生InterruptedException.(这是消息:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException
Run Code Online (Sandbox Code Playgroud)
)
但是当使用try/catch运行时,catch块中的sysout永远不会显示 - 这意味着没有捕获到这样的异常!
public class SecondThread implements Runnable{
Thread t;
SecondThread(){
t = new Thread(this, "Thread 2");
t.start();
}
public void run(){
try{
for(int i=5 ; i>0 ; i--){
System.out.println("thread 2: " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("thread 2 interrupted");
}
}
}
public class MainThread{
public static void main(String[] args){
new SecondThread();
try{
for(int i=5 ; i>0 ; i--){
System.out.println("main thread: …Run Code Online (Sandbox Code Playgroud)