Java线程可以执行不同的任务? [英] Java threads to do different tasks?

查看:97
本文介绍了Java线程可以执行不同的任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个示例代码,

I am looking at an example which code is:

class SimpleThread extends Thread {
    public SimpleThread(String str) {
        super(str);
}

public void run() {
    for (int i = 0; i < 10; i++) {
        System.out.println(i + " " + getName());
            try {
        sleep((int)(Math.random() * 1000));
        } catch (InterruptedException e) {}
    }
    System.out.println("DONE! " + getName());
    }
}

class TwoThreadsTest {
    public static void main (String args[]) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
    }
}

我的问题是:每个线程有没有一种方式可以执行自己的代码?例如,一个线程增加一个变量,而另一个线程增加另一个变量. 谢谢.

My question is: is there a way each thread does its own code? For example, one thread increments a variable, while the other thread increments other variable. Thanks.

P.S.示例的链接是: http://www. cs.nccu.edu.tw/~linw/javadoc/tutorial/java/threads/simple.html

P.S. Example's link is: http://www.cs.nccu.edu.tw/~linw/javadoc/tutorial/java/threads/simple.html

推荐答案

SimpleThread的每个实例都有其自己的本地类存储.只要您不使用标记为static的字段,每个线程都将执行自己的代码".在线程之间同步值在 上要困难得多.

Each instance of SimpleThread has it's own local class storage. As long as you aren't using fields marked as static, then each thread will "do its own code". It is much harder to synchronize values between threads.

例如:

class SimpleThread extends Thread {

    // this is local to an _instance_ of SimpleThread
    private long sleepTotal;

    public SimpleThread(String str) {
        super(str);
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " " + getName());
            try {
                long toSleep = Math.random() * 1000;
                // add it to our per-thread local total
                sleepTotal += toSleep;
                sleep(toSleep);
            } catch (InterruptedException e) {}
        }
        System.out.println("DONE!  " + getName());
    }
}

这篇关于Java线程可以执行不同的任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆