1.题目:主线程执行10次,子线程执行10次,此过程重复50次
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
package com.Thread.test;
/*
* function:主线程执行10次,子线程执行10次,
* 此过程重复50次
*/
public class ThreadProblem {
public ThreadProblem() {
final Business bus = new Business();
new Thread( new Runnable() {
public void run() {
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.四个线程,共享一个变量j,其中两个线程对j加1,两个线程对j减1。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package com.Thread.test;
//实现4个线程,两个线程加1,两个线程减1
public class Demo1 {
private static int j= 0 ;
private A a = new A();
//构造函数
public Demo1() {
System.out.println( "j的初始值为:" +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()+ "对j加1,目前j=" +Demo1.j);
}
public synchronized void delete1() {
j--;
System.out.println(Thread.currentThread().getName()+ "对j减1,目前j=" +Demo1.j);
}
}
//用于测试的主函数
public static void main(String[] args) {
Demo1 demo = new Demo1();
}
}
|