



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




65
public class State { private int cnt = 0; public int synchronized incCnt(int x) { cnt += x; } public int synchronized getCnt() { return cnt; } } public class MyThread extends Thread { State s; public MyThread(State s) { this.s = s; } public void run() { s.incCnt(1); } public void main(String args[]) { State s = new State(); MyThread thread1 = new MyThread(s); MyThread thread2 = new MyThread(s); thread1.start(); thread2.start(); } }
67
public class MyThread extends Thread { static List l = new ArrayList(); String s; // set in constructor void add(String s) { synchronized (l) { l.add(s); }} boolean check(String s) { synchronized (l) { return l.contains(s); }} public void run() { if (!check(s))add(s); } public void main(String args[]) { MyThread thread1 = new MyThread(“hello”); MyThread thread2 = new MyThread(“hello”); MyThread thread3 = new MyThread(“goodbye”); thread1.start(); thread2.start();thread3.start(); } }
68
71
72
73
74
77
78