class MyThread extends Thread {
public MyThread(int x) { a=x; } public void run() { b=a*a } public int getb() { return b; } private int a; private int b;
}
MyThread t1=new MyThread(4);
MyThread t2=new MyThread(6);
MyThread t3=new MyThread(2);
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
int sum=t1.getb()+t2.getb()+t3.getb();
16 36 4
1. class extends Thread
2. implement "run" function (abstract in thread)
3. create thread objects
4. object.start(); //not run
5. (usually) .join(); <- wait until run() ends
multitasking/scheduling
thread
t1 | 1 2 3 4 5
t2 | 1 2 3 4 5
t3 | 1 2 3 4 5
main| sum
|--------------------------------------time
class TeamMate {
public TeamMate(Schedule s) { sch = s; } public void run() { find an available slot in sch; set the meeting time; } private schedule sch;
}
you
1 2 3
462
m1=new TeamMate(myschedule);
437
m2=new TeamMate(myschedule);
independent threads competing for shared data
atomic operations
x=5;
x+=5; //not atomic; read x, add 5 to value, write the value back to x
x=f();
ATM1 ATM2
insert card insert card
enter pin enter pin
withdraw 100 withdraw 100
actions will conflict