有多个线程,每个线程随机访问一个变量,无论谁获取访问权,变量都会递增,当变量值到达30后,线程终止。
public class ThreadTest extends Thread{
//变量上线值
public final static int NUM = 30;
//计数值
public static int count = 0;
//加锁
private static byte[] lock = new byte[0];
@Override
public void run() {
while (true) {
synchronized (lock) {
if (count >= ThreadTest.NUM)
return;
count++;
System.out.println("线程"+this.getName()+"----"+count);
}
}
}
public ThreadTest(String threadName) {
super(threadName);
}
public static void main(String[] args) {
List<ThreadTest> list = new ArrayList<ThreadTest>();
for (int i = 1; i <= 5; i++)
{
ThreadTest my = new ThreadTest("Thrad " + i);
my.start();
list.add(my);
}
try
{
for (ThreadTest my : list)
{
my.join();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Over.");
}
}
执行结果
线程Thrad 1----1
线程Thrad 1----2
线程Thrad 1----3
线程Thrad 1----4
线程Thrad 1----5
线程Thrad 2----6
线程Thrad 2----7
线程Thrad 2----8
线程Thrad 2----9
线程Thrad 2----10
线程Thrad 2----11
线程Thrad 2----12
线程Thrad 2----13
线程Thrad 2----14
线程Thrad 2----15
线程Thrad 2----16
线程Thrad 1----17
线程Thrad 1----18
线程Thrad 1----19
线程Thrad 1----20
线程Thrad 1----21
线程Thrad 1----22
线程Thrad 1----23
线程Thrad 1----24
线程Thrad 1----25
线程Thrad 1----26
线程Thrad 1----27
线程Thrad 1----28
线程Thrad 1----29
线程Thrad 1----30
Over.