wait
,和notifyAll
将解决你的问题。
而不是使用单Thread类的,我会建议你使用4个不同势Thread类各1个字母
这里是工作示例中,只要是完整的代码
public class Main {
static String[] s = { "aaaaaaa", "bbbb", "ccc","ddd"};
static int status=1; // For Maintaning Order Of Processing of Threads
public static void main(String[] args) {
Main m=new Main(); // This Object's Lock is used by threads
Watek1 w1 = new Watek1(0,m);
Watek2 w2 = new Watek2(1,m);
Watek3 w3 = new Watek3(2,m);
Watek4 w4 = new Watek4(3,m);
w1.start();
w2.start();
w3.start();
w4.start();
}
}
class Watek1 extends Thread {
int i;
Main main;
public Watek1(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main)
{
for (int j = 0; j < Main.s[i].length(); j++)
{
while(main.status!=1)
{
main.wait();
}
main.status=2;
System.out.print(Main.s[i].charAt(j) + " ");
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Watek2 extends Thread {
int i;
Main main;
public Watek2(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main){
for (int j = 0; j < Main.s[i].length(); j++) {
while(main.status!=2)
{
main.wait();
}
System.out.print(Main.s[i].charAt(j) + " ");
main.status=3;
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Watek3 extends Thread {
int i;
Main main;
public Watek3(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main){
for (int j = 0,counter=0; j < Main.s[i].length(); j++) {
while(main.status!=3)
{
main.wait();
}
System.out.print(Main.s[i].charAt(j) + " ");
main.status=4;
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Watek4 extends Thread {
int i;
Main main;
public Watek4(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main){
for (int j = 0,counter=0; j < Main.s[i].length(); j++) {
while(main.status!=4)
{
main.wait();
}
System.out.print(Main.s[i].charAt(j) + " ");
main.status=1;
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
输出
a b c d a b c d a b c d a b
基本概念/逻辑后面这是,虽然1个线程执行其他线程必须等待,一旦1个线程完成它的处理它改变了状态,并且还notifyAll
线程内等待池所以能够其它线程来执行。
和状态计数器是循环为了
1------------2
| |
| |
| |
| |
4------------3
这对我没有意义。你能描述一下你真正想要的吗? – displayname 2015-02-05 17:57:29
这比你想象的更复杂,你需要使用'ThreadPool'并实现'算法'来阻止和等待。 'Thread'的正常'wait'函数不会这样做。 – 2015-02-05 17:58:51
我需要在控制台abcdabcdab ....上写字符串[] s = {“aaaaaaa”,“bbbb”,“ccc”,“dd”};我只能用一个字母来代替一个字母(一个用于a,一个用于b,一个用于c .....) – Mokbor 2015-02-05 18:20:27