public void run()
{
System.out.println(Thread.currentThread().getName() + " Start.");
for (int i = 0; i <= 100; i++)
{
if (tl.get() == null)
{
tl.set(new Integer(0));
}
int sum = ((Integer)tl.get()).intValue();
sum+= i;
tl.set(new Integer(sum));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " --- The value of sum is " + ((Integer)tl.get()).intValue());
System.out.println(Thread.currentThread().getName() + " End.");
}
}
private static void sharedVaribleTest4() throws InterruptedException
{
MyRunner3 runner = new MyRunner3();
Thread thread1 = new Thread(runner);
Thread thread2 = new Thread(runner);
thread1.setDaemon(true);
thread2.setDaemon(true);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
综上三种方案,第一种方案会降低多线程执行的效率,因此,我们推荐使用第二种或者第三种方案。
控制执行步骤控制执行步骤
说到执行步骤,我们可以使用synchronized关键字来解决它。
复制代码 代码如下:
执行步骤问题解决方案
class MySyncRunner implements Runnable
{
public void run() {
synchronized(this)
{
System.out.println(Thread.currentThread().getName() + " Start.");
for(int i = 1; i <= 5; i++)
{
System.out.println(Thread.currentThread().getName() + " Running step " + i);
try
{
Thread.sleep(50);
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " End.");
}
}