| |

VerySource

 Forgot password?
 Register
Search
View: 836|Reply: 2

Master invited: Answers to a multi-threaded question

[Copy link]

2

Threads

6

Posts

6.00

Credits

Newbie

Rank: 1

Credits
6.00

 China

Post time: 2020-1-6 18:50:01
| Show all posts |Read mode
Sorry, ask, I wrote this little program myself today

The requirements for this topic are:
There are 4 pairs of families: father, mother, son, daughter

Dads are responsible for putting apples on the plate, and moms are responsible for putting oranges on the plate.
Sons specialize in oranges on plates; daughters specialize in apples on plates;

Note; there can be no more than 10 fruits on the plate, and only one fruit can be placed or taken at a time;

That's all, the code is below, and there are some problems in running. It seems that sometimes some methods are accessed multiple times.
If you are interested, you can run the code and help me analyze the reason, thank you
class ThreadTest
{
Ransom
public static void main (String [] args)
{
Plate q = new Plate ();
Father f1 = new Father (q);
Father f2 = new Father (q);
Father f3 = new Father (q);
Father f4 = new Father (q);
Ranch
Mother m1 = new Mother (q);
Mother m2 = new Mother (q);
Mother m3 = new Mother (q);
Mother m4 = new Mother (q);
Ranch
Son s1 = new Son (q);
Son s2 = new Son (q);
Son s3 = new Son (q);
Son s4 = new Son (q);
Ranch
Daughter d1 = new Daughter (q);
Daughter d2 = new Daughter (q);
Daughter d3 = new Daughter (q);
Daughter d4 = new Daughter (q);
Ranch
f1.start ();
f2.start ();
f3.start ();
f4.start ();
Ranch
m1.start ();
m2.start ();
m3.start ();
m4.start ();
Ranch
s1.start ();
s2.start ();
s3.start ();
s4.start ();
Ranch
d1.start ();
d2.start ();
d3.start ();
d4.start ();
}
}

class Father extends Thread
{
Plate q;
Father (Plate q)
{
this.q = q;
}
public void run ()
{
while (true)
{
q.putApple (q.apple);
System.out.println (Thread.currentThread (). GetName () + "put one apple: the number of apple in the plate:" + q.apple);
}
}
}
class Mother extends Thread
{
Plate q;
Mother (Plate q)
{
this.q = q;
}
public void run ()
{
while (true)
{
q.putOrange (q.orange);
System.out.println (Thread.currentThread (). GetName () + "put one orange: the number of orange in the plate:" + q.orange);
}
}
}
Reply

Use magic Report

1

Threads

51

Posts

32.00

Credits

Newbie

Rank: 1

Credits
32.00

 China

Post time: 2020-1-7 13:27:01
| Show all posts
It may be a problem of thread synchronization
synchronized
Reply

Use magic Report

0

Threads

13

Posts

10.00

Credits

Newbie

Rank: 1

Credits
10.00

 China

Post time: 2020-1-9 21:36:01
| Show all posts
Lock it
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list