一道多线程笔试题,求大神们看看

five00000000 2015-08-31 08:58:49
加精
四个线程t1,t2,t3,t4,向4个文件中写入数据,t1只能写入1,t2只能写入2,t3只能写入3,t4只能写入4,对4个文件A,B,C,D写入如下内容:
A:123412341234.....
B:234123412341....
C:341234123412....
D:412341234123....
怎么实现同步可以让线程并行工作?
这个用java语言怎么实现呢,希望有代码噢,期待答案,多谢!
...全文
6672 58 打赏 收藏 转发到动态 举报
写回复
用AI写文章
58 条回复
切换为时间正序
请发表友善的回复…
发表回复
micro_hz 2017-03-16
  • 打赏
  • 举报
回复
忘了贴上打印结果 Thread---t1 加锁文件 t1 处理 1 Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:12 文件B:2 文件C: 文件D:4 ----------- Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 -----主线程观察文件变化---- 文件A:12341 文件B:2341 文件C:341 文件D:41 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:1234123 文件B:234123 文件C:3412 文件D:414 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:1234123412 文件B:234123412 文件C:3412 文件D:41414 ----------- Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 -----主线程观察文件变化---- 文件A:1234123412341 文件B:234123412341 文件C:3412 文件D:414141 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:123412341234123 文件B:23412341234123 文件C:3412 文件D:4141414 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:123412341234123412 文件B:23412341234123412 文件C:3412 文件D:414141414 ----------- Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 -----主线程观察文件变化---- 文件A:123412341234123412341 文件B:23412341234123412341 文件C:3412 文件D:4141414141 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:12341234123412341234123 文件B:2341234123412341234123 文件C:3412 文件D:41414141414 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:12341234123412341234123412 文件B:2341234123412341234123412 文件C:3412 文件D:4141414141414 ----------- Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 -----主线程观察文件变化---- 文件A:12341234123412341234123412341 文件B:2341234123412341234123412341 文件C:3412 文件D:41414141414141 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:1234123412341234123412341234123 文件B:234123412341234123412341234123 文件C:3412 文件D:414141414141414 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:1234123412341234123412341234123412 文件B:234123412341234123412341234123412 文件C:3412 文件D:41414141414141414 ----------- Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 -----主线程观察文件变化---- 文件A:1234123412341234123412341234123412341 文件B:234123412341234123412341234123412341 文件C:3412 文件D:414141414141414141 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:123412341234123412341234123412341234123 文件B:23412341234123412341234123412341234123 文件C:3412 文件D:4141414141414141414 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:123412341234123412341234123412341234123412 文件B:23412341234123412341234123412341234123412 文件C:3412 文件D:414141414141414141414 ----------- Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 -----主线程观察文件变化---- 文件A:123412341234123412341234123412341234123412341 文件B:23412341234123412341234123412341234123412341 文件C:3412 文件D:4141414141414141414141 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:12341234123412341234123412341234123412341234123 文件B:2341234123412341234123412341234123412341234123 文件C:3412 文件D:41414141414141414141414 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2 -----主线程观察文件变化---- 文件A:12341234123412341234123412341234123412341234123412 文件B:2341234123412341234123412341234123412341234123412 文件C:3412 文件D:4141414141414141414141414 ----------- Thread---t3 加锁文件 t3 处理 3 Thread---t2 加锁文件 t2 处理 2 Thread---t4 加锁文件 t4 处理 4 Thread---t1 加锁文件 t1 处理 1 -----主线程观察文件变化---- 文件A:12341234123412341234123412341234123412341234123412341 文件B:2341234123412341234123412341234123412341234123412341 文件C:3412 文件D:41414141414141414141414141 ----------- Thread---t4 加锁文件 t4 处理 4 Thread---t2 加锁文件 t2 处理 2
micro_hz 2017-03-16
  • 打赏
  • 举报
回复
class Files {

	private StringBuffer a;
	private StringBuffer b;
	private StringBuffer c;
	private StringBuffer d;

	Files() {
		// 四个文件初始化
		this.a = new StringBuffer();
		this.b = new StringBuffer();
		this.c = new StringBuffer();
		this.d = new StringBuffer();
	}

	public StringBuffer getA() {
		return a;
	}

	public StringBuffer getB() {
		return b;
	}

	public StringBuffer getC() {
		return c;
	}

	public StringBuffer getD() {
		return d;
	}

	public void processFile(char c) {
		System.out.println(Thread.currentThread().getName() + " 处理 " + c);
		if (c == '1') {
			if (a.length() == 0 || (a.length() > 0 && a.charAt(a.length() - 1) == '4')) {
				a.append(c);
			}

			if (b.length() > 0 && b.charAt(b.length() - 1) == '4') {
				b.append(c);
			}
			if (this.c.length() > 0 && this.c.charAt(this.c.length() - 1) == '4') {
				this.c.append(c);
			}
			if (d.length() > 0 && d.charAt(d.length() - 1) == '4') {
				d.append(c);
			}
		} else if (c == '2') {
			if (b.length() == 0 || (b.length() > 0 && b.charAt(b.length() - 1) == '1')) {
				b.append(c);
			}

			if (a.length() > 0 && a.charAt(a.length() - 1) == '1') {
				a.append(c);
			}
			if (this.c.length() > 0 && this.c.charAt(this.c.length() - 1) == '1') {
				this.c.append(c);
			}
			if (d.length() > 0 && d.charAt(d.length() - 1) == '1') {
				d.append(c);
			}
		} else if (c == '3') {
			if (this.c.length() == 0 || (this.c.length() > 0 && this.c.charAt(this.c.length() - 1) == '1')) {
				this.c.append(c);
			}

			if (a.length() > 0 && a.charAt(a.length() - 1) == '2') {
				a.append(c);
			}
			if (b.length() > 0 && b.charAt(b.length() - 1) == '2') {
				b.append(c);
			}
			if (d.length() > 0 && d.charAt(d.length() - 1) == '2') {
				d.append(c);
			}
		} else if (c == '4') {
			if (d.length() == 0 || (d.length() > 0 && d.charAt(d.length() - 1) == '1')) {
				d.append(c);
			}

			if (a.length() > 0 && a.charAt(a.length() - 1) == '3') {
				a.append(c);
			}
			if (this.c.length() > 0 && this.c.charAt(this.c.length() - 1) == '3') {
				this.c.append(c);
			}
			if (b.length() > 0 && b.charAt(b.length() - 1) == '3') {
				b.append(c);
			}
		}
	}

}
// 模拟四个文件
		final Files files = new Files();
		new Thread(new Runnable() {

			@Override
			public void run() {
				synchronized (files) {
					while (true) {
						try {
							Thread.currentThread().sleep(500);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
						files.notifyAll(); // 唤醒其他线程
						System.out.println("Thread---" + Thread.currentThread().getName() + " 加锁文件 ");
						files.processFile('1');
						try {
							files.wait(); // 释放锁
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}, "t1").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				synchronized (files) {
					while (true) {
						try {
							Thread.currentThread().sleep(500);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
						files.notifyAll(); // 唤醒其他线程
						System.out.println("Thread---" + Thread.currentThread().getName() + " 加锁文件 ");
						files.processFile('2');
						try {
							files.wait(); // 释放锁
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}, "t2").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				synchronized (files) {
					while (true) {
						try {
							Thread.currentThread().sleep(500);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
						files.notifyAll(); // 唤醒其他线程
						System.out.println("Thread---" + Thread.currentThread().getName() + " 加锁文件 ");
						files.processFile('3');
						try {
							files.wait(); // 释放锁
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}, "t3").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				synchronized (files) {
					while (true) {
						try {
							Thread.currentThread().sleep(500);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
						files.notifyAll(); // 唤醒其他线程
						System.out.println("Thread---" + Thread.currentThread().getName() + " 加锁文件 ");
						files.processFile('4');
						try {
							files.wait(); // 释放锁
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}, "t4").start();

		StringBuffer a = files.getA();
		StringBuffer b = files.getB();
		StringBuffer c = files.getC();
		StringBuffer d = files.getD();
		while (true) {
			try {
				// 主线程休眠
				Thread.currentThread().sleep(2000);
				System.out.println("-----主线程观察文件变化----");
				System.out.println("文件A:" + a);
				System.out.println("文件B:" + b);
				System.out.println("文件C:" + c);
				System.out.println("文件D:" + d);
				System.out.println("-----------");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
balahala 2015-09-09
  • 打赏
  • 举报
回复
看不懂啊。。。。。。。。。
zhengwei060024 2015-09-07
  • 打赏
  • 举报
回复
结果
zhengwei060024 2015-09-07
  • 打赏
  • 举报
回复
c++的
#include "stdafx.h"
#include <Windows.h>
#include <string>
#include <iostream>
#include <process.h>
using namespace std;
HANDLE hWorkDoneEvent = NULL;
volatile long nLength[4] ={ 0 };
std::string str1[4];
char szWrite[4]={'1','2','3','4'};
unsigned __stdcall WorkThreadItem(void* ParamThreadID)
{
long Myparam = (long)ParamThreadID;
while (true)
{
for(int i = 0 ;i < 4; ++i)
{
if (Myparam == (nLength[i]&3) && nLength[i] <=200)
{
str1[i] += szWrite[(Myparam + i) &3];
++nLength[i];
}
}
if (nLength[0] >=200 && nLength[1] >=200 && nLength[2] >=200 && nLength[3] >=200)
{
SetEvent(hWorkDoneEvent);
break;
}
}
return 0;

}
int _tmain(int argc, _TCHAR* argv[])
{

for (int i = 0;i < 4;++i)
{
nLength[i] = str1[i].length();
}
unsigned threadID;

hWorkDoneEvent = CreateEvent(NULL,true,false,_T("WorkDone"));
ResetEvent(hWorkDoneEvent);

for (int i = 0; i < 4; ++i)
{
_beginthreadex( NULL, 0, WorkThreadItem,(void*) i, NULL,&threadID);
}

WaitForSingleObject(hWorkDoneEvent,INFINITE);

for (int i = 0; i < 4; ++i)
{
cout << str1[i] << endl << endl;
}
getchar();
return 0;
}


将 字符数组换成文件就可以了。
牧童吃五谷 2015-09-07
  • 打赏
  • 举报
回复
1.建立4个类对象,每个类对象中有4个信号量 class CThreadFile { public: BYTE* pFileBytes; DWORD FileLength; HANDLE hEvent[4];//分别对应4个线程处理的信号量,信号量为自动复位的 }; CThreadFile ThreadFile[4];//建立4个文件类对象 2.主线程启动4个辅助线程,然后根据每个文件第一个字节的内容,分别设置4个信号量的发信号状态 2.4个辅助线程分别循环等待每个文件中的每个信号量,即每个辅助线程等待4个信号量 辅助线程根据信号量状态存储文件内容,然后根据文件的下一个字节的内容,设置信号量状态
zhengwei060024 2015-09-07
  • 打赏
  • 举报
回复
看看,学习下。
业余草 2015-09-07
  • 打赏
  • 举报
回复
引用 7 楼 henuyx 的回复:
第一个线程直接往A中写 12341234...... 第二个线程直接往B中写23412341...... 第三个线程直接往C中写34123412...... 第四个线程直接往D中写41234123...... 别跟我说没看清题意,我懒的思考...
rooke_zc 2015-09-07
  • 打赏
  • 举报
回复
4楼高手啊,我安全看不懂的说
zhengwei060024 2015-09-07
  • 打赏
  • 举报
回复
没注意看题目,循环里面有些问题。t1只能写入1,t2只能写入2,t3只能写入3,t4只能写入4
 if (Myparam == (nLength[i]&3) && nLength[i] <=200)
            {
                str1[i] += szWrite[(Myparam + i) &3];
                ++nLength[i];
            }
应该改为
if (Myparam == (((nLength[i] + i)&3)) && nLength[i] <=200)
			{
				str1[i] += szWrite[Myparam];
				++nLength[i];
			}
完整代码如下:
#include "stdafx.h"
#include <Windows.h>
#include <string>
#include <iostream>
#include <process.h>
using namespace std;
HANDLE  hWorkDoneEvent = NULL;
volatile long nLength[4] ={ 0 };
std::string str1[4];
char szWrite[4]={'1','2','3','4'};
unsigned __stdcall  WorkThreadItem(void* ParamThreadID)
{
	long Myparam = (long)ParamThreadID;
	while (true)
	{
		for(int i = 0 ;i < 4; ++i)
		{
			if (Myparam == (((nLength[i] + i)&3)) && nLength[i] <=200)
			{
				str1[i] += szWrite[Myparam];
				++nLength[i];
			}
		}
		if (nLength[0] >=200 && nLength[1] >=200 && nLength[2] >=200 && nLength[3] >=200)
		{
			SetEvent(hWorkDoneEvent);
			break;
		}
	}
	return 0;

}
int _tmain(int argc, _TCHAR* argv[])
{
	
	for (int i = 0;i < 4;++i)
	{
		nLength[i] = str1[i].length();
	}
	unsigned threadID;

	hWorkDoneEvent = CreateEvent(NULL,true,false,_T("WorkDone"));
	ResetEvent(hWorkDoneEvent);
	
	for (int i = 0; i < 4; ++i)
	{
		_beginthreadex( NULL, 0, WorkThreadItem,(void*) i, NULL,&threadID);
	}

	WaitForSingleObject(hWorkDoneEvent,INFINITE);

	for (int i = 0; i < 4; ++i)
	{
		cout << str1[i] << endl << endl;
	}
	getchar();
	return 0;
}
HaoYuan 2015-09-07
  • 打赏
  • 举报
回复
哈哈 前几天笔试刚考过类似的题,不过我是用C语言写的!
weizhaom 2015-09-06
  • 打赏
  • 举报
回复
纯当练习 c#解决方案 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { FileStream streamA = new FileStream(@".\1.text", FileMode.Create, FileAccess.ReadWrite,FileShare.ReadWrite); FileStream streamB = new FileStream(@".\2.text", FileMode.Create, FileAccess.ReadWrite); FileStream streamC = new FileStream(@".\3.text", FileMode.Create, FileAccess.ReadWrite); FileStream streamD = new FileStream(@".\4.text", FileMode.Create, FileAccess.ReadWrite); StreamWriter writerA = new StreamWriter(streamA); StreamWriter writerB = new StreamWriter(streamB); StreamWriter writerC = new StreamWriter(streamC); StreamWriter writerD = new StreamWriter(streamD); //1 Task.Factory.StartNew(() => { writerA.Write(1); writerA.Flush(); queB.Enqueue(writerA); while (true) { if (queA.Count>0) { StreamWriter w = queA.Dequeue(); if (w == null) { continue; } w.Write(1); w.Flush(); queB.Enqueue(w); } } } ); //2 Task.Factory.StartNew(() => { writerB.Write(2); writerB.Flush(); queC.Enqueue(writerB); while (true) { if (queB.Count > 0) { StreamWriter w = queB.Dequeue(); if (w == null) { continue; } w.Write(2); w.Flush(); queC.Enqueue(w); } } }); //3 Task.Factory.StartNew(() => { writerC.Write(3); writerC.Flush(); queD.Enqueue(writerC); while (true) { if (queC.Count > 0) { StreamWriter w = queC.Dequeue(); if (w == null) { continue; } w.Write(3); w.Flush(); queD.Enqueue(w); } } }); //4 Task.Factory.StartNew(() => { writerD.Write(4); writerD.Flush(); queA.Enqueue(writerD); while (true) { if (queD.Count > 0) { StreamWriter w = queD.Dequeue(); if (w == null) { continue; } w.Write(4); w.Flush(); queA.Enqueue(w); } } }); Console.ReadKey(); } static Queue<StreamWriter> queA = new Queue<StreamWriter>(); static Queue<StreamWriter> queB = new Queue<StreamWriter>(); static Queue<StreamWriter> queC = new Queue<StreamWriter>(); static Queue<StreamWriter> queD = new Queue<StreamWriter>(); } }
熬夜程序圆 2015-09-06
  • 打赏
  • 举报
回复
这个功能挺强大的 学洗了 诶 赚个分真不容易
ztxd666888 2015-09-04
  • 打赏
  • 举报
回复
学习了,多谢
cattpon 2015-09-04
  • 打赏
  • 举报
回复
learning~
猪哥66 2015-09-03
  • 打赏
  • 举报
回复
这是检测结果,当然我还有个简单的方法,但是我觉得这个更实用,更通俗易懂;
猪哥66 2015-09-03
  • 打赏
  • 举报
回复
感觉四楼的并没有实现四个文件并行写入,而是一个一个写入,这里我给大家贴一个自己写的代码;先说说我的思路: /* 四个线程t1,t2,t3,t4,向4个文件中写入数据,t1只能写入1,t2只能写入2,t3只能写入3,t4只能写入4,对4个文件A,B,C,D写入如下内容: A:123412341234..... B:234123412341.... C:341234123412.... D:412341234123.... 怎么实现同步可以让线程并行工作? */ 四个文件并行工作,四个线程A-D ,四个线程t1-t4分别写入1-4,这又是四个所以先把这几个线程列出来,然后再往里面添加代码,最后再去测试,我的方法虽然复杂,但是思路清晰易懂,而且还有一个优点就是ABCD这四个文件写1234的顺序可以传入,随你怎么写,下面是我的代码:
package hellojava;

import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Hello
{
	static boolean b=false;
	static ReentrantLock lock=new ReentrantLock();         
	static ReentrantLock lock_2=new ReentrantLock();
	static Condition condition_for=lock.newCondition();

//线程Thread_t1~Thread_t4分别只写入1~4
	class Thread_t1 extends Thread
	{
		String path;
		Thread_t1(String path)
		{
			this.path=path;
		}
		public void run()
		{
			print(path,1);
		}
	}
	
	class Thread_t2 extends Thread
	{
		String path;
		Thread_t2(String path)
		{
			this.path=path;
		}
		public void run()
		{
			print(path,2);
		}
	}
	
	class Thread_t3 extends Thread
	{
		String path;
		Thread_t3(String path)
		{
			this.path=path;
		}
		public void run()
		{
			print(path,3);
		}
	}
	
	class Thread_t4 extends Thread
	{
		String path;
		Thread_t4(String path)
		{
			this.path=path;
		}
		public void run()
		{
			print(path,4);
		}
	}
	
//写入方法
	public void print(String path, int i)
	{
		lock_2.lock();
		PrintWriter pw=null;
		try {
				pw=new PrintWriter(new FileWriter("c:/work/abcd/"+path+".txt",true),true);
				pw.print(i);
				
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				pw.close();
				lock_2.unlock();
			}
	}
	
//文件类A~D
	class File_A implements Runnable
	{
		int one,two,three,four;
		
		File_A(int one,int two, int three, int four)
		{
			this.one=one;
			this.two=two;
			this.three=three;
			this.four=four;
		}
		
		public void run()
		{
			for(int x=0;x<100;x++)
			{
				select("A",one,two,three,four);
			}
		}
	}
	
 	class File_B implements Runnable
	{
		int one,two,three,four;
		File_B(int one,int two, int three, int four)
		{
			this.one=one;
			this.two=two;
			this.three=three;
			this.four=four;
		}
		
		public void run()
		{
			for(int x=0;x<100;x++)
			{
				select("B",one,two,three,four);
			}
		}
	}
	
	class File_C implements Runnable
	{
		int one,two,three,four;
		File_C(int one,int two, int three, int four)
		{
			this.one=one;
			this.two=two;
			this.three=three;
			this.four=four;
		}
		
		public void run()
		{
			for(int x=0;x<100;x++)
			{
				select("C",one,two,three,four);
			}
		}
	}
	
	class File_D implements Runnable
	{
		int one,two,three,four;
		File_D(int one,int two, int three, int four)
		{
			this.one=one;
			this.two=two;
			this.three=three;
			this.four=four;
		}
		
		public  void  run()
		{
			for(int x=0;x<100;x++)
			{
				select("D",one,two,three,four);
			}
		}
	}
//选择线程方法,当前只允许进入一个文件线程
	public   void select(String path,int one,int two, int three, int four)
	{
		lock.lock();
		try
		{
			while(b)
			{
				 condition_for.await();
			}
			b=true;
		    int[] order={one,two,three,four};//将传入的1234,换成数组方便用for遍历
		    for(int i:order)
		    {
			    switch(i){
			    
		    	   case 1:
				        Thread_t1 t1= new Thread_t1(path);
				        t1.start();
				        t1.join();          //t1.join()是等线程t1执行完后再执行当前线程
				        break;

		    	   case 2:
				        Thread_t2 t2= new Thread_t2(path);
				        t2.start();
				        t2.join();
				        break;

		    	   case 3:
				        Thread_t3 t3= new Thread_t3(path);
				        t3.start();
				        t3.join();
				        break;
				        
		    	   case 4:
				        Thread_t4 t4= new Thread_t4(path);
				        t4.start();
				        t4.join();
				        break;
			           }	
		}
		b=false;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
	}
	
//主函数
	public static void main(String args[])
	{
		HelloJava hj=new HelloJava();
		new Thread(hj.new File_A(1,2,3,4)).start();
		
		new Thread(hj.new File_B(2,3,4,1)).start();
		
		new Thread(hj.new File_C(3,4,1,2)).start();
		
		new Thread(hj.new File_D(4,1,2,3)).start();

	}
}
whzxcvbnm 2015-09-02
  • 打赏
  • 举报
回复
我也来一发,同步主要靠synchronized和CyclicBarrier
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class WriteIntoFiles {
	
	//写文件代码因为不是重点就用打印语句代替了
	public void writeA(String x) {
		System.out.println(x + "write File A");
	}
	
	public void writeB(String x) {
		System.out.println(x + "write File B");
	}
	
	public void writeC(String x) {
		System.out.println(x + "write File C");
	}
	
	public void writeD(String x) {
		System.out.println(x + "write File D");
	}

	private CyclicBarrier cyc = new CyclicBarrier(4);
	
	public static void main(String[] args) {
		WriteIntoFiles w = new WriteIntoFiles();
		Thread t1 = new Thread (new Number(w, "A", "1",w.cyc));
		Thread t2 = new Thread (new Number(w, "B", "2", w.cyc));
		Thread t3 = new Thread (new Number(w, "C", "3",w.cyc));
		Thread t4 = new Thread (new Number(w, "D", "4", w.cyc));
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}

}
class Number implements Runnable {
	
	WriteIntoFiles wif;
	String target;
	String n;
	CyclicBarrier cb;
	
	public Number(WriteIntoFiles w, String target, String num, CyclicBarrier cb) {
		wif = w;
		this.target = target;
		n = num;
		this.cb = cb;
	}
	
	public void run(){
		while(true) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			write();
		}
	}
	
	public synchronized void write() {
		switch(target) {
		case "A" :
			wif.writeA(n);
			target = "D";
			break;
		case "B" :
			wif.writeB(n);
			target = "A";
			break;
		case "C" :
			wif.writeC(n);
			target = "B";
			break;
		case "D" :
			wif.writeD(n);
			target = "C";
			break;
		}
		try {
			cb.await();
		} catch (InterruptedException e) {		
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
	}
}
gw6328 2015-09-02
  • 打赏
  • 举报
回复
把数字做成临界资源 并加锁就可以了。java我不了解。 c#大概如下 private int GetNumber(){ lock(ob){ num++; if(num>4) num=1; return num; } } 开4个线程调这个方法。 这只能是题,现实中不可能这样子做。
five00000000 2015-09-02
  • 打赏
  • 举报
回复
引用 31 楼 codeck 的回复:
这道题目主要是考虑程序员对性能的理解,实现方法很多,但要注意算法,我觉得求模处理这个问题最合适不过了。 定义一个变量存放模的范围,你这里最大数是4,那么模就是4. 线程1,2,3,4分别对应一个文件,每个线程独立对应一个文件,这样减少了判断,增强了执行效率。 每个线程在执行一次就自增1再求模,可以如下理解: 线程1, 执行是 0%4 = 0 , 1%4=1, 2%4=2 ,3%4= 3 , 结果0123 不是我们要取的值,所以结果必须都+1变成1234.所以 0%4 = 0 +1 , 1%4=1 +1, 2%4=2 +1,3%4= 3 +1 . 4 %4 =0+1 , 5%4=1+1,可以一直循环下去 线程234跟线程1同理,只是它们的初始值分别变成 1,2,3。 这样的好处是性能最大化。互相不干扰,也不会出错。
若能给出实现代码就更好了
加载更多回复(37)

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧