弄的我茶饭不思的多线程理解!
有一个问题,我一直很迷茫!希望大哥大姐仔细看完,帮我理透一下多线程的思路
如:有一个类Test,没有成员变量,就只有一些静态方法
public class Test { public static void test(int i,int j){ /* *这里是自己写的一些业务,做了一些逻辑操作,处理一些数据 * / System.out.println(i+j); }}
package com.keeya.test;import keeya.util.*;public class ThreadTest extends Thread { public static int i = 0 , j = 0 ; public void run() { i++; j++; Test.test(i, j); } public static void main(String[] args) { Thread thread1 = new ThreadTest(); Thread thread2 = new ThreadTest(); Thread thread3 = new ThreadTest(); Thread thread4 = new ThreadTest(); Thread thread5 = new ThreadTest(); Thread thread6 = new ThreadTest(); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); thread6.start(); } }class Test { public static void test(int i,int j){ MyOwnerPrint.println("This is {0} and i = {1}, j = {2}",Thread.currentThread(),i,j); int temp = 100000000; while(temp-- > 0); MyOwnerPrint.println("This is {0} and i + j = {1}",Thread.currentThread(),i+j); }}
------解决方案--------------------
每个线程都有自己独立的空间(这个空间大小可进行设置的),其将需要运行的方法独自封闭在自己的线程栈中运行。运行时,方法中局部变量的值不会互相影响,会影响的值只是成员变量,因为成员变量是被线程所共享的,并不会复制到自己独立的运行空间中去。如果没有成员变量,就不存在线程安全问题。
[解决办法]
绝对会 混淆的了 除非
public static synchronized void test(int i,int j){ /* *这里是自己写的一些业务,做了一些逻辑操作,处理一些数据 * / System.out.println(i+j); }
[解决办法]
很简单的,如果你有用到全局变量就有关系。如果只是局部变量就没关系。
[解决办法]