Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Data{
- private String name;
- synchronized public void setName(){
- name = Thread.currentThread().getName();
- print("before: " + name);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException x) {
- }
- print("after: " + name);
- };
- public static void print(String msg) {
- System.out.println(Thread.currentThread().getName() + ": " + msg);
- }
- }
- class Sync implements Runnable{
- private Data data;
- Sync(Data dt){data = dt;}
- public void run() {
- data.setName();
- }
- }
- public class SynchronizedMethod{
- public static void main(String[] args) throws Exception{
- Data id = new Data();
- Sync runA = new Sync(id);
- Sync runB = new Sync(id);
- Thread ta = new Thread(runA, "threadA");
- Thread tb = new Thread(runB, "threadB");
- ta.start();
- tb.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement