我使用100个线程求sum+1的和100次。使用了synchronized为什么还是不能正确求和呢,每次不都是只有一个线程能运行run()吗。结果应该是100。但打印出来的有99,77等,每次都不一样。
package Thread;class newRunnable implements Runnable{
private int sum =0;
public synchronized void run(){
sum+=1;
Thread.yield();
}
public void print(){
System.out.println(sum);
}
}public class MyRunnable{
public static void main(String[] args){
newRunnable x = new newRunnable();
for(int i=0;i<2;++i){
new Thread(x).start();
}
x.print();
}
}
package Thread;class newRunnable implements Runnable{
private int sum =0;
public synchronized void run(){
sum+=1;
Thread.yield();
}
public void print(){
System.out.println(sum);
}
}public class MyRunnable{
public static void main(String[] args){
newRunnable x = new newRunnable();
for(int i=0;i<2;++i){
new Thread(x).start();
}
x.print();
}
}
new Thread(x).start();
}
x.print();这样不能保证主线程在所有子线程执行完后才打印吧
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
可以阻止其他的线程访问run方法,但不能阻止它访问其它的方法(print)
class newRunnable implements Runnable{
private int sum =0;
public void run(){
synchronized(this)
{
sum=sum+1;
}
}
public void print(){
System.out.println("1--->"+sum);
}
}public class MyRunnable{
public static void main(String[] args){
newRunnable x = new newRunnable();
for(int i=0;i<100;i++){
new Thread(x).start();
}
x.print();
}
}
看看下面的程序可以吗?
class newRunnable implements Runnable{
private int sum =0;
public void run(){
synchronized(this)
{
sum=sum+1;
}
}
public void print(){
System.out.println("1--->"+sum);
}
}public class MyRunnable{
public static void main(String[] args){
newRunnable x = new newRunnable();
Thread t = null;
for(int i=0;i<100;i++){
t = new Thread(x);
t.start();
try{
t.join();
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
x.print();
}
}
private int sum =0;要变成static的
private static int sum =0;从而所有线程共享变量
2要等所有线程运行完成以后再打印结果x.print();
private int sum = 0;
public void run(){
sum++;
}
public void print(){
System.out.println(sum);
}
}public class MyRunnable{
public static void main(String[] args){
newRunnable x = new newRunnable();
for(int i=0;i<100;i++){
new Thread(x).start();
}
while (Thread.activeCount()>1){}
x.print();
}
}