我的目標是啓動三個未同步的線程並讓它們各自添加一千個元素。這些元素需要存儲在一個集合中(我選擇Vector)然後打印。出於某種原因,我沒有獲得要打印的元素。我試圖解決打印方法和創建元素的方法。任何幫助表示讚賞。將元素添加到線程的矢量並打印它們 - Java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
public class MyRun implements Runnable{
int global = 0;
//create sets
static Vector t1v = new Vector();
static Vector t2v = new Vector();
static Vector t3v = new Vector();
public void run() {
action1();
}
public void action1() {
for(int i = 0; i < 1000; i++) {
global++;
int x = global;
String tName = Thread.currentThread().getName();
if(tName == "t1") {
t1v.addElement(x);
System.out.println(t1v.elementAt(x));
}
if(tName == "t2") {
t2v.addElement(x);
}
if(tName == "t3") {
t3v.addElement(x);
}
//System.out.println("thread: " + tName + "counter is: " + global);
}
}
public static Vector gett1v() {
return t1v;
}
public static Vector gett2v() {
return t2v;
}
public static Vector gett3v() {
return t3v;
}
}
class ThreadTest{
public static void main(String[] args) {
//create threads
Runnable threadJob = new MyRun();
Thread t1 = new Thread(threadJob);
t1.setName("thread1");
Thread t2 = new Thread(threadJob);
t2.setName("thread2");
Thread t3 = new Thread(threadJob);
t3.setName("thread3");
t1.start();
t2.start();
t3.start();
Vector th1v = MyRun.gett1v();
Vector th2v = MyRun.gett2v();
Vector th3v = MyRun.gett3v();
//MyRun.printSets();
for(int i=0; i < th1v.size(); i++) {
System.out.println("Thread 1: " + th1v.elementAt(i));
}
for(int i=0; i < th2v.size(); i++) {
System.out.println("Thread 2: " + th2v.elementAt(i));
}
for(int i=0; i < th3v.size(); i++) {
System.out.println("Thread 3: " + th3v.elementAt(i));
}
}
}
歡迎來到Stack Overflow!你已經在你的問題中發佈了很多代碼,這使得我們(以及未來的讀者)不清楚問題出在哪裏。請將您的問題代碼減少到10行或更少。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)和[如何調試小程序](https://ericlippert.com/2014/03/05 /如何調試的小程序/)。 –
恐怕有很多問題。你選擇了一個不贊成的,非多線程安全的類,比如'Vector'來保存元素,在這之上你不會同步消費者和生產者。再加上非原子全局。嗯,和不匹配的線程名稱(與對象相等比較,在這種情況下,由於interning,但可能蠕變一些開發人員):) –