1、怎样使一个方法是线程安全的?
下面的方法是线程安全的吗?怎么使它线程安全?
class MyCounter {
private static int counter = 0;
public static int getCount() {
return counter++;
}
}
方法不是线程安全的,因为counter++操作不是原子操作的,意味着它由多个原子操作组成。这种情况下,一个线程在访问值,另外一个线程在增加值
方法一:添加synchronize能使得方法是线程安全的
class MyCounter {
private static int counter = 0;
public static synchronized int getCount() {
return counter++;
}
}
方法二:使变量是原子整数import java.util.concurrent.atomic.AtomicInteger;
public class MyCounter {
private static AtomicInteger counter = new AtomicInteger(0);
public static int getCount() {
return counter.getAndIncrement();
}
}
2、线程重写Runnable的例子
class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
}
class B implements Runnable
{
public void run()
{
new A().run();
new Thread(new A(), "name_thread2").run();
new Thread(new A(), "name_thread3").start();
}
}
public class Main
{
public static void main(String[] args)
{
new Thread(new B(), "name_thread1").start();
}
}
new Thread().start()是创建线程,然后在创建的线程中执行run中的代码
而new Thread().run()只是在当前线程中执行代码