Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Resource{
- public String name;
- public Resource(String name){
- this.name = name;
- }
- public String getName(){
- return name;
- }
- }
- class ThreadA extends Thread{
- private Resource R1;
- private Resource R2;
- public ThreadA(Resource res1, Resource res2){
- this.R1 = res1;
- this.R2 = res2;
- }
- public void run(){
- synchronized(R1){
- System.out.println("ThreadA locked "+R1.getName());
- try{
- Thread.sleep(100);
- }catch(InterruptedException e){
- System.out.println(e);
- }
- synchronized(R2){
- System.out.println("ThreadA locked "+R2.getName());
- System.out.println("ThreadA is using resources.");
- }
- }
- }
- }
- class ThreadB extends Thread{
- private Resource R1;
- private Resource R2;
- public ThreadB(Resource res1, Resource res2){
- this.R1 = res1;
- this.R2 = res2;
- }
- public void run(){
- synchronized(R2){
- System.out.println("ThreadB locked "+R2.getName());
- try{
- Thread.sleep(100);
- }catch(InterruptedException e){
- System.out.println(e);
- }
- synchronized(R1){
- System.out.println("ThreadB locked "+R1.getName());
- System.out.println("ThreadB is using resources.");
- }
- }
- }
- }
- public class Main{
- public static void main(String[] args){
- Resource res1 = new Resource("Resource A");
- Resource res2 = new Resource("Resource B");
- ThreadA t1 = new ThreadA(res1,res2);
- ThreadB t2 = new ThreadB(res1,res2);
- t1.start();
- t2.start();
- try{
- t1.join();
- t2.join();
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println("Main thread finished");
- }
- }
Add Comment
Please, Sign In to add comment