Java sum传递需要我们不断的学习,当然我们在学习中会有很多的问题需要我们解决。下面我们就详细的来看看不能更好的启动100个线程。每个线程给变量Java sum传递加1(sum初始值为0)。需要通过引用传递,将sum传递给线程。
为了能够进行引用传递,将sum作为一个类成员变量,并将该类的对象传递给线程。使用加锁和不加锁两种方式实现加1操作,看看最终的执行效果。
- */
- public class Thread100Baidu {
- public static void main(String[] args) {
- int[] sum = new int[100];
- MyThread[] mt = new MyThread[100];
- for(int i=0;i<sum.length;i++) {
- sum[i] = i;
- mt[i] = new MyThread(sum[i]);
- mt[i].start();
- }
- }
- }
- class MyThread extends Thread {
- int sum = 0;
- public MyThread(int sum) {
- this.sum = sum;
- }
- public synchronized void run() {
- while(sum<100) {
- System.out.println(currentThread().getName() + " sum= " + sum);
- sum++;
- }
- }
- }
- /*
Java sum传递编写3个线程,一个线程给某个对象里的整型变量赋初值,第二个线程给初值加10,第三个线程给变量值清0,要求这3个线程严格按照赋初值、加10、清0顺序执行,使用多线程的共享与同步的方式实现。
- public class ThreeThreadBaidu {
- public static void main(String[] args) {
- Myobject mo = new Myobject(0);
- FirstThread ft = new FirstThread(mo);
- ft.start();
- SecondThread st = new SecondThread(mo);
- st.start();
- ThirdThread tt = new ThirdThread(mo);
- tt.start();
- }
- }
- class Myobject {
- int i;
- public Myobject(int i) {
- this.i = i;
- }
- }
- class FirstThread extends Thread {
- Myobject mo = null;
- public FirstThread(Myobject mo) {
- this.mo = mo;
- }
- public synchronized void run() {
- mo.i = 100;
- System.out.println(currentThread().getName()+ " 初始值 = " + mo.i);
- }
- }
- class SecondThread extends Thread {
- Myobject mo = null;
- public SecondThread(Myobject mo) {
- this.mo = mo;
- }
- public synchronized void run() {
- mo.i += 10 ;
- System.out.println(currentThread().getName()+ " 加10后 = " + mo.i);
- }
- }
- class ThirdThread extends Thread {
- Myobject mo = null;
- public ThirdThread(Myobject mo) {
- this.mo = mo;
- }
- public synchronized void run() {
- mo.i = 0 ;
- System.out.println(currentThread().getName()+ " 清0后 = " + mo.i);
- }
- }
以上就是对Java sum传递的详细介绍。
【编辑推荐】