62,616
社区成员
发帖
与我相关
我的任务
分享
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();
}
}
#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;
}
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;
}
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();
}
}
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();
}
}
}