我想并排执行多条线程。例如:
ex:会有一个简单的计数器方法,线程将访问该方法并打印计数器值。一个线程在开始之前不应该等待另一个线程停止。并行执行多条线程
样品输出[也许]:
T1 1
T2 1
T1 2
T1 3
T1 4
T2 2
T1 5
我没有事先关于多线程的想法,只是想学习。
我想并排执行多条线程。例如:
ex:会有一个简单的计数器方法,线程将访问该方法并打印计数器值。一个线程在开始之前不应该等待另一个线程停止。并行执行多条线程
样品输出[也许]:
T1 1
T2 1
T1 2
T1 3
T1 4
T2 2
T1 5
我没有事先关于多线程的想法,只是想学习。
如果在计数器共享你想要的东西是这样的:
class ThreadTask implements Runnable {
private static AtomicInteger counter = new AtomicInteger();
private int id;
public ThreadTask(int id) { this.id = id; }
public void run() {
int local = 0;
while((local = counter.incrementAndGet()) < 500) {
System.out.println("T" + id + " " + local);
}
}
}
...
new Thread(new ThreadTask(0)).start();
new Thread(new ThreadTask(1)).start();
否则,如果你想有一个每线程计数器:
class ThreadTask implements Runnable {
private int counter = 0;
private int id;
public ThreadTask(int id) { this.id = id; }
public void run() {
while(counter < 500) {
counter++;
System.out.println("T" + id + " " + counter);
}
}
}
...
new Thread(new ThreadTask(0)).start();
new Thread(new ThreadTask(1)).start();
不具有实际的问题....
我想你可以启动多个线程,并让他们访问synchonised printCounter方法。
喜欢的东西
public class MyRunnable implemetns Runnable {
private SharedObject o
public MyRunnable(SharedObject o) {
this.o = o;
}
public void run() {
o.printCounter();
}
}
然后开始你可以做
new Thread(new MyRunnable()).start();
new Thread(new MyRunnable()).start();
等
然后在您的共享对象方法,你想有保存,您可以打印一个变量法。这种方法也可以增加计数器。
虽然线程调度程序不保证线程何时运行,但请注意。
你还没有真正问过任何特定的东西。如果你只是寻找一个非线程安全的计数器的一般例子是跨越两个或多个线程共享的,在这里你去:
public class Counter extends Thread {
private static int count = 0;
private static int increment() {
return ++count; //increment the counter and return the new value
}
@Override
public void run() {
for (int times = 0; times < 1000; times++) { //perform 1000 increments, then stop
System.out.println(increment()); //print the counter value
}
}
public static void main(String[] args) throws Exception {
new Counter().start(); //start the first thread
new Counter().start(); //start the second thread
Thread.sleep(10000); //sleep for a bit
}
}
您已经发布了一个“我想要”,但毫无疑问呢。当然你已经阅读过关于线程的教程,对吧?你坚持什么具体步骤? –
并排启动线程。对于计数器1-500,较高优先级的线程应该比较慢的优先级线程完成更快。 – Sourav
学习的最好方法就是开始做。简单的多线程代码有数百万个例子,所以我会从其中的一些开始。 –