Java多线程

合集下载
相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

▪ Therefore,
mt.start();
// Starts thread running at run()
// Returns immediately
Copyright © 2001 Stephen A. Edwards All rights reserved
Thread Basics
▪ A thread is a separate program counter
▪ All objects can be shared among threads
▪ Fundamentally nondeterministic
▪ Language provide some facilities to help avoid it
Copyright © 2001 Stephen A. Edwards All rights reserved
Thread 2 a.field1 = 1
f2 = a.field2
a.field2 = 2
Copyright © 2001 Stephen A. Edwards All rights reserved
Races
▪ Interleaved execution ▪ Thread 1 sees one new value, one old value
Copyright © 2001 Stephen A. Edwards All rights reserved
Races
▪ Thread 1 goes first ▪ Thread 1 reads original values
Thread 1 f1 = a.field1
Thread 2 a.field1 = 1
f2 = a.field2
a.field2 = 2
Copyright © 2001 Stephen A. Edwards All rights reserved
Races
▪ Thread 2 goes first ▪ Thread 1 reads new values
Thread 1 f1 = a.field1
Concurrency in Java
Prof. Stephen A. Edwards
Copyright © 2001 Stephen A. Edwards All rights reserved
Concurrency in Java
▪ Language supports threads
▪ Multiple contexts/program counters running within the same memory space
Copyright © 2001 Stephen A. Edwards All rights reserved
The Sleep Method
public void run() {
for(;;) {
try {
sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
return;
// caused by thread.interrupt()
}
System.out.println(“Tick”);
}
}
Copyright © 2001 Stephen A. Edwards All rights reserved
The Sleep Method
Does this print Tick once a
second? No.
sleep() delay a lower bound
public void run() { for(;;) { try {
Rest of loop takes indeterminate amount of time
sleep(1000);
} catch (InterruptedException e) {
… and stack, local variables, etc.
▪ Not an object or a collection of things
▪ Classes, objects, methods, etc. do not belong to a thread
▪ Any method may be executed by one or more threads, even simultaneously
Thread 1 f1 = a.field1
Thread 2 a.field1 = 1
f2 = a.field2
a.field2 = 2
Copyright © 2001 Stephen A. Edwards All rights reserved
Non-atomic Operations
▪ 32-bit reads and writes are guaranteed atomic ▪ 64-bit operations may not be
▪ Other threads are your adversary
▪ Consider what can happen when simultaneously reading and writing:
Thread 1
f1 = a.field1
f2 = a.field2
Thread 2 a.field1 = 1 a.field2 = 2
return;
ห้องสมุดไป่ตู้
}
System.out.println(“Tick”);
}
}
Copyright © 2001 Stephen A. Edwards All rights reserved
Races
▪ In a concurrent world, always assume someone else is accessing your objects
Thread Basics
▪ How to create a thread:
class MyThread extends Thread { public void run() { /* thread body */ }
}
MyThread mt = new MyThread; // Create thread
相关文档
最新文档