1. Topic: main thread Execution 10 times, child thread execution 10 times, this process repeats 50 times
Code:
Package com.
Thread.test; * * Function: main thread execution 10 times, child thread execution 10 times, * This process repeats 50 times/public class Threadproblem {public Threadproblem () {final busines
s bus = new Business ();
New Thread (New Runnable () {public void run () {A for (int j=0;j<50;j++) {bus.sub (j);
}}). Start ();
for (int j=0;j<50;j++) {bus.main (j);
} class Business {private Boolean tag=true;
Public synchronized void sub (int num) {if (!tag) {try {this.wait ();
catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
for (int i=0;i<10;i++) {System.out.println ("sub thread" +i+, loop "+num+");
} Tag=false;
Notify ();
Public synchronized void main (int num) {if (tag) {try {this.wait ();
catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
for (int i=0;i<10;i++) {System.out.println ("main thread" +i+ ", Loop" +num+ ");
}
Tag=true;
Notify ();
} public static void Main (string[] args) {Threadproblem problem = new Threadproblem ();
}
}
2. Four threads, sharing a variable J, where two threads to J plus 1, two threads to J minus 1.
The code is as follows:
Package com. Thread.test;
Implement 4 threads, two threads plus 1, two threads minus 1 public
class Demo1 {
private static int j=0;
Private A A = new A ();
Constructor public
Demo1 () {
System.out.println ("J's initial value is:" +j);
for (int i=0;i<2;i++) {
new Thread (new Runnable () {public
void Run ()} {for
(int k=0;k<5;k++)
{ A.ADD1 ();
}
}
). Start ();
New Thread (New Runnable () {public
void run () {for
(int k=0;k<5;k++)
{
a.delete1 ()}
}
}). Start ();
}
Class A {public
synchronized void Add1 () {
j + +;
System.out.println (Thread.CurrentThread (). GetName () + "to J plus 1, currently j=" +DEMO1.J);
}
Public synchronized void Delete1 () {
j--;
System.out.println (Thread.CurrentThread (). GetName () + "to J minus 1, currently j=" +DEMO1.J);
}
The main function for testing is public
static void Main (string[] args) {
Demo1 demo = new Demo1 ();
}